Java:Basics – Interfaces

Like Python, Ruby and other languages, Java is big on inheritance. One can define functionality in a super class and extend that into sub classes (sub classes inheriting from the parent class.)

Abstraction

In Java, you can define a parent class as being abstract.  More than that, you can define the methods in the class as abstract as well.  This allows the methods to be named, but defined in sub classes.

For example, the parent class Animal can have abstract methods like feed and pet.  These abstract methods will have no formal definition and would look like this:

public abstract void feed();
public abstract void pet();

Child classes would make use of the keyword “extend” to extend the functionality of the parent class.  Then using the @Override annotation like so:

public class Capybara extends Animal {
   @Override
   public void feed(){
        [some code would go here]
   }
}

Interfaces

An interface is an abstract class with no variables and only abstract method declarations.  This allows something interesting.  With inheritance a child class can only have one parent.  But with interfaces you can have multiple points of inheritance.

This way if you had two base classes such as Animal and Color, then a black Capybara could inherit from both base classes.

This is written like so:

public interface Animal {
    public abstract void feed();
}

The classes inheriting would use call like this:

public class Capybara implements Animal{
    [some code goes here]
}

Leave a Reply

Your email address will not be published. Required fields are marked *