Interface

Another important structure other than a class is an Interface.
An Interface is similar to class except an Interface could only contain method signatures (with no implementation) and fields until Java 8. By default all unimplemented methods are abstract and public in an interace.

What is an abstract method?

An abstract method is a method that is declared, but contains no implementation. Abstract classes are classes that contain one or more abstract methods. Abstract classes cannot be instantiated. Generally one of the subclasses will provide implementations for the abstract methods.


abstract class Book {

     private String title;
     private String author;
     private double price;

     public void setTitle(String title) {
         this.title = title;
     }
     public void setAuthor(String author) {
         this.author = author;
     }
     public void setPrice(double price) {
         this.price = price;
     }

     public String getTitle() {
         return this.title;
     }
     public String getAuthor() {
         return this.author;
     }
     public double getPrice() {
         return this.price;
     }
     public abstract String getFormat();
 }

class EBook extends Book {

    private String url;

    public void setUrl(String url) {
        this.url = url;
    }

    public String getFormat(){
        return "epub";
    }
}

class HardCoveredBook extends Book {

    private int qtyInStock;

    public void setQtyInStock(int qty) {
        this.qtyInStock= qty;
    }

    public String getFormat() {
            return "kdp";
    }
}

Note the book class has to be declared abstract class as it contains an abstract method:

public abstract String getFormat();

The reason you declare the method abstract is because the implementation of the method will be different for each child. Each child class will decide how to override and implement the abstract method of the parent. The child should either implement the abstract method or declare itself abstract if it decides not to implement the method.

In an interface all methods are abstract by default, even if you do not declare them to be abstract.

What is an interface?

In real world any type of interface is an intermediate device which connects two separate systems. For e.g., if you consider your mobile phone, the on/off switch is an interface. You as the user press the interface button on or off and the interface passes this command to the system at the other side of the button which will turn on or off your mobile phone. When your mobile phone stops working for any reason, you take it to the repair shop and the repair man may replace the hardware system on the other side of the on/off button, leaving the button alone. The new hardware starts working when you press the on/off switch. So what happened here is, the interface remained the same, but the working implementation of the button was replaced and you the user are still able to use the same on/off button of the interface even though the hardware changed on the other side.

This is precisely the behavior you emulate using an interface in Java. An interface is a construct which sits between two separate programming entities.
A class which implements the interface will provide the actual working of the methods that are declared in the interface. Another system can invoke this class using the interface.


interface ShippingAddress {

    public void setShippingAddress();

}

class Book{

     private String title;
     private String author;
     private double price;

     public void setTitle(String title) {
         this.title = title;
     }
     public void setAuthor(String author) {
         this.author = author;
     }
     public void setPrice(double price) {
         this.price = price;
     }

     public String getTitle() {
         return this.title;
     }
     public String getAuthor() {
         return this.author;
     }
     public double getPrice() {
         return this.price;
     }
 }

class EBook extends Book implements ShippingAddress {

    private String emailAddress;

    private String shippingAddress;

    public void setEmailAddress(String emailId) {
        this.emailAddress = emailId;
    }
    public void setShippingAddress() {

        this.shippingAddress = this.emailAddress;
    }
}

class HardCoveredBook extends Book implements ShippingAddress {

    private String mailingAddress;

    private String shippingAddress;

    public void setMailingAddress(String mailingAddress) {
        this.mailingAddress = mailingAddress;
    }

    public void setShippingAddress() {

        this.shippingAddress = this.mailingAddress;
    }
}

In the above example, we declared an interface called ShippingAddress. Any class which implements this interface should give implementation for the shipping address. For an EBook, shipping address is nothing but the EmailId of the customer. But for a HardCoveredBook, shipping address is the mailing address of the customer. So you give the correct implementation for the interface method in the class which implements it.

Java 8 changes to Interface: Java 8 allows the interfaces to have default and static methods. Once these method are declared default or static in the interface, the implementing class does not need to implement it. While default methods can be overridden, static method cannot be overridden.

Here is an example:



interface MyInterface{  
    /* This is a default method so we need not
     * implement this method in the implementation 
     * classes  
     */
    default void newMethod(){  
        System.out.println("Newly added default method");  
    }  

    /* This is a static method. Static method in interface is
     * similar to default method except that we cannot override 
     * them in the implementation classes.
     * Similar to default methods, we do not hav eto implement these methods
     * in implementation classes so we can safely add them to the 
     * existing interfaces.
     */
    static void anotherNewMethod(){
        System.out.println("Newly added static method");
    }
    /* This is the regular public abstract method by default
     * Should be implemented in the 
     * implementation classes.
     */
    void existingMethod(String str);  
}  
public class Example implements MyInterface{ 
    // implementing abstract method
    public void existingMethod(String str){           
        System.out.println("String is: "+str);  
    }  
    public static void main(String[] args) {  
        Example obj = new Example();

        //calling the default method of interface
        obj.newMethod();     
        //calling the static method of interface
        MyInterface.anotherNewMethod();

        //calling the implemented method in the implementing class
        obj.existingMethod("Java 8 is easy to learn"); 


    }  
}

Points to note

  • An interface cannot be instantiated
  • An interface cannot have method implementations with earlier versions of Java. But from Java 8 onwards, this has changed and now methods with default, static and private(Java 9 onwards) keywords can have implementations.
  • Every variable declared in an interface is public, static and final by default.

Polymorphism

Polymorphism (from the Greek word meaning: having multiple forms) is the ability for an object to take different forms at different points of time. In Java Polymorphism is implemented using Inheritance and Interface. Let us study the above example of Books, EBooks and HardCoveredBook and the interface ShippingAddress.

An EBook is a child of Book. So we say that any object created using EBook IS-A Book and also an EBook. This is because EBook is a child of Book. So in other words, every child object is not only the class that it is instantiated from but is also its parent, grand parent, great grand parent etc.. This means that you can declare a variable of any of the super classes and can assign an object that is instantiated out of any of its sub classes. Lets see the below example:


public class BookStore {

    public static void main(String[] args) {
        Book book1 = new EBook();
        ShippingAddress shippingAddress = new EBook();
    }
}

In the above example, we instantiated an EBook with the new keyword and assigned that object to a variable which is of type Book. Since Book is a superclass of EBook, this is allowed. In the second line, you also see that we are able to instantiate an EBook and assign that to a variable of type ShippingAddress. ShippingAddress is an interface which is implemented by EBook and thus you are allowed to assign the object instance of EBook to ShippingAddress. It is in this way that an object of one type is able to take the form of another by virtue of either inheriting the class or by implementing the interface.

Points to note

  • You can implement polymorphism in Java in two ways; applying parent/child inheritance mechanism and another implementing interface
  • An interface can extend another interface
  • In Java you can implement multiple interfaces, separating each one with a comma; MyClass implements interface1, interface2 etc..
  • In Java, you can only inherit from one class; MyClass extends MySuperClass
  • Abstract class cannot be instantiated.

results matching ""

    No results matching ""