Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a method that is present in both interface and abstract class in java

I am trying to understand what happens if a method is present in both an abstract class and an interface. Below, I posted a scenario that gives you a clear idea of what I am referring to.

interface act
{
    void read();
}

abstract class enact
{
    void read() {
        System.out.println("hello");
    }
}

public class second extends enact implements act  
{
    public void read() {

        // does method read() correspond to  Interface or abstract class?
    }
}

Surprisingly,there is no compilation error when I write this code. Any suggestions would be highly helpful.

like image 584
mohan babu Avatar asked Oct 19 '22 18:10

mohan babu


2 Answers

I am just curious to know whether the method read() relates to interface or abstract class

Or neither, really. It depends on the apparent type in the context where you actually use it. E.g. whether you do

enact example = new second();

or

act example = new second();

Both allow you to compile the code:

example.read();

because the read() method is defined in both apparent types, act and enact. But in both cases, it's the read() definition defined in the "second" class that really matters. That's what gets executed.

like image 200
Riaz Avatar answered Oct 22 '22 02:10

Riaz


I am not sure what kind of problems you expect so I will try to show that there are no problems with this scenario.

You are calling methods from references like:

Second sc = new Second();//you should name your classes with upper-case
sc.read(); 

and this will execute code from Second class because that is type of object stored in sc reference (this is how polymorphism works - or to be precise dynamic binding).

You could also create instance of Second class and pass it to reference of Act type (all types in Java should start with upper-case, including interfaces, and enums) like

Act act = sc;// or Act act = new Second();
act.read();

Since read() method is polymorphic (only final, private or static methods aren't) at runtime JVM will look for code to execute in class which instance is stored in art interface, so since it is instance of Second class code of read() from that class will be executed (if you would not override it in that class code inherited from Enact abstract class will be executed).

like image 22
Pshemo Avatar answered Oct 22 '22 01:10

Pshemo