Monday, October 17, 2016

Java Interface and Multiple Inheritance

Interface in java is to support multiple inheritance. What is multiple inheritance? a good question to ask. Multiple inheritance means you inherit property from many individuals. Take yourself as an example, you inherit properties from your mother and your father. A java class also need to inherit properties from other classes. We do this inheritance by extends keyword, it means we extends the class from super class. But extends keyword only valid for one class. for example :
package com.example.myapplication.alert;

/**
 * Created by SONY on 17/10/2016.
 */
public class Child extends Father {
}

It is not valid to extends from two classes like below :
package com.example.myapplication.alert;

/**
 * Created by SONY on 17/10/2016.
 */
public class Child extends Father, Mother {
}

And it is not valid also to write extends two times like below :
package com.example.myapplication.alert;

/**
 * Created by SONY on 17/10/2016.
 */
public class Child extends Father extends Mother {
}

But like in the real world, you need the child inherit properties from mother and father (not just from mother only or father only). Now, I want a child has white skin like his mother and black hair like his father. Okay, that is why we have interface. Let's do that.

Below we define an interface IMother with setSkinWhite() method:
package com.example.myapplication.alert;

/**
 * Created by SONY on 17/10/2016.
 */
public interface IMother {
    public void setSkinWhite();
}


And below we define interface IFather with setHairBlack() method:
package com.example.myapplication.alert;

/**
 * Created by SONY on 17/10/2016.
 */
public interface IFather {
    public void setHairBlack();
}

Now let's make  Child that inherit both IMother and IFather properties.

package com.example.myapplication.alert;

/**
 * Created by SONY on 17/10/2016.
 */
public class Child implements IMother, IFather {
    @Override
    public void setHairBlack() {
        
    }

    @Override
    public void setSkinWhite() {

    }
}


From the above code you see that Child implements both IMother and IFather. So now that child inherits property from his mother and his father. That's it. That is multiple inheritance in java.

Thank you for visiting our website. Just comment below if you have any question to ask.

No comments:

Post a Comment