Ahmad Raza
Ahmad Raza

Reputation: 145

What is a difference between direct inheritance and indirect inheritance in java?

I am new to JAVA and just started learning Direct and indirect inheritance in java but couldn't get much .I want to visualize how these two are different and when we should be using indirect and direct inheritance ?

Upvotes: 1

Views: 1836

Answers (1)

ItFreak
ItFreak

Reputation: 2369

Direct inheritance means that you explicitly write A extends B. Indirectly means you inherit from a class that is extended by B, in Java for example Object. This results in class A having a toString() method which is indirectly inherited from Object (lets assume that B does not declare a explicit toString)

When it comes to methods, you only inherit the last one that was overidden. Lets assume that B does have a custom toString method, class A will have this and not the default one from object.

Code example:
class B:

public class B (extends Object) //to clarify {
 @Override
 public void toString() {...}
}

class A:

public class A extends B {
  toString(); //will call Bs toString.
  //If B would not have a custom toString, the toString of Object would be executed
}

Upvotes: 6

Related Questions