Interface

Another important structure other than a class is an Interface. An Interface is similar to class except an Interface can only contain method signatures and fields. An Interface does not contain implementation of the methods and all methods are by default abstract.

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 method overriding?

If the child class has the same method signature as the parent, then it is called overriding. The child class (a.k.a subclass) will override the parent method as it needs to give a different implementation for the same method. Let us take an example:


class Animal{

    public void speak(){

        System.out.println("Every animal speaks in its own way");
    }
}

class Cat extends Animal{

    public void speak(){
        System.out.println("meow meow");
    }

}


public class AnimalKingdom{

    public static void main(String[] args){
        Animal animal = new Animal();
        animal.speak();

        Cat myCat = new Cat();
        myCat.speak();

    }
}

In the above example, the Cat class overrides the speak method of the Animal as it is giving specific way in which a Cat speaks.

Run the above code and see the output. What do you see? Now remove the speak method in Cat and then run the same program. What do you see now? Do you understand why the output is different?

bulb It is called overriding only if the method signatures match between the parent and the child class. If the parameter list is different between the parent and child class then it is called overloading.

What is method overloading?

Method overloading is a feature that allows a class to have more than one method having the same name, but with different arguments list.


class MyMath{

    public static void main(String[] args){

        int a = calculate(5,6);
        int b = calculate(5,6,"subtract");
        System.out.println(a);
        System.out.println(b);
    }

    public static int calculate(int a, int b){
        return a+b;
    }

    public static int calculate(int a, int b, String method){
        switch (method){
            case "add":
                return a+b;
            case "subtract":
                return a-b;
         }

         return 0;

    }
}

In the above class, you see two methods with the same name calculate. However, the parameters list is different. First calculate method takes two integer parameters and the second method takes two integer parameters and one string parameter.

Rules for overloading

  • The return type of the overloaded methods should be the same
  • Overloaded methods cannot have the same method signature. This is the fundamental principle of overloading

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.

Points to note

  • An interface cannot be instantiated

  • An interface cannot have method implementations

  • Every variable and method declared in an interface is 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 als object created using EBook IS-A Book and 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.

results matching ""

    No results matching ""