Interfaces in Java – Part 2

When you define an interface if you make interface public then any class can access it and if you did not use word of public then it will only accessible to classes define in same package.

It can have multiple parent interfaces.

Interfaces as types

Moreover we can use an interface as a type in classes just like other variable types. But if you are using interface type variable in a class then you must have to implement that class with that interface. And also any child class which is extended from previously called class can be using that interface type. Look at the below example.

public interface I {
    String printName();
}
@Override
public String printName() {
return "A Class";
    }
public class A2 extends A {
    @Override
public String printName() {
return "A2 Class";
    }
}
public class B {
public static void main(String[] args) {
        I tempI = new A();
System.out.println(tempI.printName());
tempI = new A2();
System.out.println(tempI.printName());
    }
}

Upgrade an old interface

When you need to add new methods to your interface you can just add new methods as usual. But whoever developers has implemented your interface to their classes, have to update their classes and recompile again. This scenario is a great barrier. There are few way to manage this process with updating existing implemented classes.

  1. Introduce a new interface extending old interface and add new methods to new interface.

These scenario developers can choose options either proceed with old interface implementation or upgrade with new interface. It is up to developer and no problem arises. Check the below code snippets.

  1. Use of Default methods.

Go through my java default method article.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s