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"?
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.
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!
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.
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”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With