Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interface and inheritance in java

I have a question of how to relate interface to inheritance, for example:

if class A implements interface X, also class A is the superclass of class B and class C, my question is , does it mean both class B and class c will automatically implement interface X as well?

like image 838
pei wang Avatar asked Sep 14 '26 19:09

pei wang


2 Answers

It depends if class A is an abstract class or not. Assuming that class A fully implements interface X then both B and C will implement X. For example each line of code would be perfectly fine...

X one = new A();
X two = new B();
X three = new C();
like image 94
Jeff Richley Avatar answered Sep 16 '26 10:09

Jeff Richley


if class A implements interface X, also class A is the superclass of class B and class C, my question is , does it mean both class B and class c will automatically implement interface X as well?

Not if A has an implementation. Otherwise, yes they need to.

public interface X{ public void stuff();} 

public class A implements X { 
   // A not abstract, must implement "stuff()" 
   // therefore, B and C will automatically have an implementation of "stuff()" too
}

but if A is abstract

public abstract A implements X {
    // not implemented.  B and C will need to implement
    public abstract void stuff(); // not implemented 
}
like image 25
MadConan Avatar answered Sep 16 '26 10:09

MadConan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!