Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java abstract class implements an interface, both have the same method

While looking at some OOP materials, I thought of this question which confused me a little bit:

Consider having the following interface,abstract class, and a concrete class:

package one;

public interface A {

    void doStuff();
}

package one;


public abstract class B implements A {

    public abstract void doStuff();


}

class C extends B{


    public void doStuff() {

    }
 }

Class C won't compile unless it provides an implementation for method doStuff(). The question here:

1-Is doStuff() method in class C an implementation to the interface A's method, or it is for the abstract method in class B ? to be more specific: How will the JVM treat the function, as an invoked function of the interface or the abstract class ?

2-Is the abstract method doStuff() in abstract class B considered to be an "implementation" for the doStuff() method in interface A? so that makes it mandatory for class C to implement the abstract class's version of doStuff() instead of the interface's ?

like image 672
a.u.r Avatar asked Mar 04 '13 13:03

a.u.r


2 Answers

For Question #1: The doStuff method in class C is the implementation of the doStuff method declaration to both B and C. because the doStuff method declaration in abstract class B and interface A has the same signature as each other. Actually, if B implements C, there is no need to declare doStuff method again.

For Question #2: No, the doStuff in B is just a declaration, not a method implementation. if B has no method implementation or additional method declaration, it is needless of class B. Basically, the abstract class is a kind of template containing high-level logic for the convenience of its subclasses.

like image 59
Henry Leu Avatar answered Sep 29 '22 07:09

Henry Leu


In an interface, all methods are public and abstract.

Knowing this, interface A's doStuff is actually public abstract void doStuff(). Which should look familiar, as Abstract Class B has the same method signature.

To answer question 1, class B's doStuff() is the same as interface A's doStuff(). Since all methods in Java are virtual, calling doStuff() will be the same regardless of if your C is declared as an A, a B, or a C.

As for question 2, no. B's doStuff() is redundant code that doesn't actually do anything. C is implementing A's doStuff() whether or not B declares doStuff().

like image 38
Powerlord Avatar answered Sep 29 '22 06:09

Powerlord