Jay Zhang
Jay Zhang

Reputation: 629

Confusion on call Java Interface method

Let's say I have an interface A, defined as follows:

public interface A {
    public void a();
}

It includes a method called a.

I have a class which implements this interface and it has only one method:

public class AImpl implements A {
    @Override
    public void a() {
        System.out.println("Do something");
    }
}

Q: If, in the main class I call the interface method, will it call the implementation belonging to the class which implements the interface?

For example:

public static void main(String[] args) {
    A aa;
    aa.a();
}

Will this print "Do something"?

Upvotes: 25

Views: 91241

Answers (5)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

A aa = new AImpl();
aa.a();

Here your reference variable is interface A type But actual Object is AImpl.

When you define a new interface, you are defining a new reference data type. You can use interface names anywhere you can use any other data type name. If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface.

Read more on Documentation

A Interface reference can hold Object of AImpl as it implements the A interface.

Upvotes: 33

jlordo
jlordo

Reputation: 37813

It depends on the runtime type of the object. See:

This is your interface:

public interface A {
  public void a();
}

And this is your class:

public class AImpl implements A {
    public void a() {
       println("I am AImpl");
    }
}

There is another implementation:

public class AnotherAImpl implements A {
    public void a() {
       println("I am another AImpl");
    }
}

So have a look at the this main method:

public static void main(String[] args){
  A aa;
  aa = new AImpl();
  aa.a(); // prints I am AImpl
  aa = new AnotherAImpl();
  aa.a(); // now it prints I am another AImpl
}

Upvotes: 26

Johan Sjöberg
Johan Sjöberg

Reputation: 49187

You need to invoke the routine on the actual AImpl object

A aa = new AImpl();
aa.a();

which here is equivalent to following

AImpl aa = new AImpl();
aa.a();

Your sample will raise an error since you're trying invoke a method on an uninitalized object.

Upvotes: 2

No. I will not.

You have declared a variable. You should initialze it first with instance of an object in this case your class AImpl.

public static void main(String[] args){
  A aa = new AImp();
  aa.a();
}

Upvotes: 1

Vindicare
Vindicare

Reputation: 213

You could probably find this out by running the code yourself.

Currently you will get a NullPointerException because you haven't assigned anything to the variable aa. Changing your code to the following will invoke the method and output the text:

public static void main(String[] args){
    A aa = new AImpl();
    aa.a();
}

Upvotes: 2

Related Questions