gameover
gameover

Reputation: 12013

Java inheritance doubt

  1. A class in Java cannot extend more than one class.

  2. Every class in Java extends java.lang.Object .

  3. From 1 and 2: Any class in Java cannot extend any other class other than java.lang.Object.

What is wrong in this deduction ?

Upvotes: 2

Views: 173

Answers (4)

Jay
Jay

Reputation: 27464

Inheritance is a tree. A class can only DIRECTLY extend one class, but that class could extend another which extends another, etc. So you can say A extends Object, B extends A, C extends B, etc. C inherits from Object indirectly.

Upvotes: 1

Sean
Sean

Reputation: 29772

Correct statements:

  1. A class in Java cannot directly extend more than one class.

  2. Every class in Java extends java.lang.Object, directly or indirectly.

Upvotes: 2

aperkins
aperkins

Reputation: 13114

To extend on what Tangens said:

For number 2, it should instead read:

Every class that does not explicitly declare a class it extends extends Object

i.e. if you use the extends keyword, you are now saying that you explicitly extend something other than Object. However, at some point, that extension path will end up back at Object, if you follow the extension hierarchy.

The other part of this is that inheritance is really a chain - you have all of the properties of your parent and their parent and their parent's parent etc. Since the top of this hierarchy is always Object, you must, at one level or another, extend Object.

Upvotes: 4

tangens
tangens

Reputation: 39733

You can only extend one class at a time. But A can extend B can extend C and so on.

Upvotes: 7

Related Questions