Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion on call Java Interface method

Tags:

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

public interface A {   public void a(); } 

It includes method called void a();

I have a class which implements this interface and 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 interface method, will it call the implementation belonging to class which implements the interface?

For example:

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

Will this print "Do something"?

like image 541
Jay Zhang Avatar asked Apr 23 '13 16:04

Jay Zhang


People also ask

Can you call a method from an interface in Java?

In order to call an interface method from a java program, the program must instantiate the interface implementation program. A method can then be called using the implementation object.

What is the default method of call interface?

Default methods have an implemented function body. To call a method from the super class you can use the keyword super , but if you want to make this with a super interface it's required to name it explicitly. Output: Hello ParentClass!

Can we call interface method in Java 8?

Interfaces can have default methods with implementation in Java 8 on later. Interfaces can have static methods as well, similar to static methods in classes. Default methods were introduced to provide backward compatibility for old interfaces so that they can have new methods without affecting existing code.

Can we call interface in abstract class?

Interface can't provide the implementation of an abstract class. Inheritance vs Abstraction: A Java interface can be implemented using the keyword “implements” and an abstract class can be extended using the keyword “extends”.


1 Answers

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.

like image 65
Subhrajyoti Majumder Avatar answered Nov 14 '22 14:11

Subhrajyoti Majumder