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();
public String printName() {
return "A Class";
public class A2 extends A {
public String printName() {
return "A2 Class";
public class B {
public static void main(String[] args) {
        I tempI = new A();
tempI = new A2();

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.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

Create a free website or blog at

Up ↑

%d bloggers like this: