How can a class extend two classes in Java?
Solution 1
If java can only extend one class, and every class extends java.lang.Object, how can it extend another class?
When you say A extends B then it means that A extends B and B extends Object
. One class can inherit from another which can inherit from another and at the top of the chain is java.lang.Object
. Java doesn't support multiple inheritance , but supports multi-level inheritance.
how come every class doesn't have written "extends Object" ?
All classes extend Object
implicitly , so it will be redundant coding.
Solution 2
Since java.lang.Object is the parent of every object in Java, you don't have to explicitly write extends Object
You can always extend any class. If you need to have behavior of 2 classes - you need to use interfaces for that
Solution 3
Every class in Java extends implicitly class Object
, and you only have the permission to extend one more class, and infinite number of interfaces.
Same as having one default constructor for each class if you didn't write a constructor.
So when you say
class A{
}
it is actually looks like this:
class A extends Object{
A(){
super();
}
}
But when you say when you say
class B extends A
In this case class B will have the features of class A, and because A extends Object, class B will also inherit class Object.
A -> Object
B -> A
So
B -> Object
Solution 4
The one and only that you are allowed to extend also extends the class Object
ultimately.Hence you are not extending twice.
Comments
-
splitgames almost 2 years
If Java can only extend one class, and every class extends
java.lang.Object
, how can it extend another class? And how come every class doesn't have writtenextends Object
?