Fact 1:
Java does not support multiple inheritance.
Fact 2:
Object is a superclass of all other classes
If I have a class Parent and a class Child which is inheriting the class Parent:
class Parent {
}
class Child extends Parent {
}
In this case, how will the class Child inherit the Object class, if Java does not support multiple inheritance?
How is the relationship between these three defined?
Option 1:
Option 2:
It's Option 2. If you define a superclass, that will be the immediate superclass of your class. If you don't define one, Object will be the immediate superclass.
class Parent {
}
class Child extends Parent {
}
is equivalent to
class Parent extends Object {
}
class Child extends Parent {
}
So, while Object is the superclass of all classes, there might be some steps in the class hierarchy before you get to Object. It's not the immediate superclass of all classes.
Object might not be a direct parent, but it's always a super parent.
Child extends Parent
Parent extends Object
|
V
Child [indirectly] extends Object
The JavaDoc says:
Class Object is the root of the class hierarchy. ...
If a class does not extend any other class by decalring it using the keyword extends it extends though implicit from Object.
The documentation says:
In the absence of any other explicit superclass, every class is
implicitly a subclass of Object.
See the Example 8.1.4-1 "Direct Superclasses and Subclasses" in JLS, chapter 8.1.4
It shows that a class Point { int x, y; } "is a direct subclass of Object"
Moreover the documentation says:
Classes can be derived from classes that are derived from classes that
are derived from classes, and so on, and ultimately derived from the
topmost class, Object. Such a class is said to be descended from all
the classes in the inheritance chain stretching back to Object.
The JLS states it short and formal:
The subclass relationship is the transitive closure of the direct
subclass relationship.
Thus class Object is the superclass of all classes.
But the documentation also says:
Excepting Object, which has no superclass, every class has one and only one direct superclass (single
inheritance).
Going on with the example a class ColoredPoint extends Point { int color; } "is a direct subclass of class Point.". By the transitive relationship it's a (non-direct) subclass of class Object.
Summarizing:
Object is either the direct superclass or by transitive relationship the last superclass of any other class.
Answering the questions:
Java does not support multiple inheritance: It provides single inheritence in a transitive way. Every class extends directly only one supercalss.
How is the relationship: The class Parent corresponds to the class Point and the class Child to the class ColoredPoint of the JLS example. Only Option 2 shows this relation.
Well it is an interesting discussion. I think it will be option no 2. As if you try the below code .
public static void main(String []args){
Parent p=new Parent();
Class c= p.getClass();
Child child =new Child();
Class c1= child.getClass();
System.out.println(c.getSuperclass());
System.out.println(c1.getSuperclass());
}
You will get output as :
class java.lang.Object
class Parent
Option 2, as every object derives Object.class methods
The right answer is Option 2. Any Java class inherit all parents for their parents. In other words.
Class A extends Class B
Class B extends Class C
Class C extends Class D
Class X extends A -> it means that A inherit all protected/package/public fields from B,C and D.
In your example, Class Child inherit Parent properties but also Object properties in transitive mode.
From Class Object
public class Object
Class Object is the root of the class hierarchy.
Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.
This means that every Java class has Object as root in the hierarchy, not necessarily as its immediate parent.
No multiple inheritance means in Java a class extends only 1 class; has one immediate base class. Indirectly a class can have many ancestors: Child has Parent and Object as ancestor "super" classes.
Object --> Parent --> Child
--> OtherChild
Relation: 1 --> N
The reason for avoiding multiple inheritance like in C++, was the ambiguity involved:
Pseudo code assuming multiple inheritance:
class A : Comparable
class B : Comparable
class Child : A, B {
#Override A? B?
int compareTo(Child rhs) { ... super.compareTo ? ... }
}
A a = new Child();
B b = new Child();
a.compareTo(b);
First of all, using Java 8, it is possible to accomplish Multiple inheritance using Default methods of interfaces.
Secondly, your understanding regarding Object class is correctly represented in 'Option 2'.
However, it is not multiple inheritance, rather multilevel inheritance. 'Option 1' is multiple inheritance.
Please check this link to read more about them.
option 2.Object is a superclass of all other classes,but Object may not a dirrect superclass of a classe.
Related
This question already has answers here:
Java : If A extends B and B extends Object, is that multiple inheritance
(11 answers)
Closed 3 years ago.
All classes in Java are inherited from Object class by default.
Then how the class inherited can inherit other classes?
Java do not support Multiple inheritance, right?
Classes inherit from at least and at most one class,
Either from Object implicitly (without writing extends), or from other class explicitly (as extends YourParentClass)
Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object
Because each class inherit from Object or from class inherit from Object, each class still inherit from Object, for example toString() method
If your custom class inherit from different class, still at the end of the hierarchy, the parent class will be Object, notice that classes hierarchy isn't multiple inheritance:
The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes
At the top of the hierarchy, Object is the most general of all classes. Classes near the bottom of the hierarchy provide more specialized behavior.
As you already correctly stated, all classes in Java are inherited from Object class by default. That means that any class that does NOT have an extends clause defined, implicitly has written extends Object. Example
class Animal // implicitly written extends Object
{}
On the other hand, if a class has an extends clause, then it does not directly inherit from Object. But its parent class inherits from object. As inheritance is transitive, therefore the class also inherits the functions of Object. Example
class Dog extends Animal {}
class Animal // implicitly written extends Object
{}
This means Dog is an Animal and Animal is an Object. Therefore Dog is an Object. You could write Object o = (Object) new Dog(); and that would totally be fine.
This can go arbitrarily deep. For example you could now have a class Poodle which inherits Dog which inherits Animal which inherits Object. Therefore a Poodle is an Object.
By using inheritance , a child class will inherit object class through parent class.
What you are talking about is known as - Multilevel inheritance.
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class, thereby making this derived class the base class for the new class.
i.e. - A is Object class, B is the base class that you want to inherit and C is your child class.
btw Java 8 has introduced default method to handle basic multiple inheritance problem ( though I don't agree that it solves the actual problem) - check default methods in Java 8
I know that super will be called every time we create a child class object. But, what I specifically want to know is that will it load the class or will it create the object of that parent class.
Thanks in advance.
You have a single object.
As a class is instantiated, it invokes first the constructor of the parent class. And for each parent class, it follows the same logic : it invokes first the constructor of the parent class.
Suppose : A extends B extends C.
new A() results to the B constructor invocation that invokes itself the C constructor.
As C then B constructor invocations are returned, the A constructor can go on and the instance A is created.
But, what I specifically want to know is that will it load the class
or will it create the object of that parent class.
Similarly to the constructor execution, before loading a class, its parent class has to be loaded first and that recursively for each parent class.
Here classes corresponding to A extends B extends C :
class C {
public C(){
System.out.println("C constructor");
}
}
class B extends C{
public B() {
System.out.println("B constructor");
}
}
class A extends B{
public A() {
System.out.println("A constructor");
}
}
public class Test {
public static void main(String[] args) {
new A();
}
}
Compile these classes and then execute the Test class that creates a A instance in its main() method by specifying the -verbose flag (enable by default the classes logs) in the java command :
java -verbose Test
And you should see in the output standard something like :
[Loaded java.lang.Object from C:\...]
[Loaded java.io.Serializable from C:\...]
... // load all classes required until loaded C, B and A classes
[Loaded C from file:/C:/...]
[Loaded B from file:/C:/...]
[Loaded A from file:/C:/...]
C constructor
B constructor
A constructor
It confirms that :
the parent classes need to be loaded first by starting by the root parent class ( Object) until the closest parent class(B).
no constructor is executed before all classes of the hierarchy be loaded
the constructors of the parent classes are always executed before the constructor of the instantiated class by starting by the root parent constructor ( Object) until the closest parent constructor(B).
The constructor is called, therefore an object of the parent class is created. That object is used later to build an object of the child class. The reason for this is that an object of the child class is an object of the parent class with more things.
Because the child class inherits properties and methods from the parent class, the entire class hierarchy (including superclasses and implemented interfaces) are loaded.
When you create an instance of the childclass, only a single object of type childclass is created (instantiated). There are no additional instances of any parent(s).
The properties and methods declared on parent classes are accessible via the childclass instance, and due to this inheritance the childclass instance will be accepted as argument to any methods that expect an instance of the parent (or any interfaces that it or any parent implements).
If you think of the code as a contractual design, this makes perfect sense:
The parent class declaration establishes that certain methods are available to call on itself or any of its children. The same is true for interfaces. For example, all employment contracts in the real world must contain certain clauses, but the rest is up to the company.
By inheriting (extends or implements) it is guaranteed that the child will also automatically provide the same methods. For example, we can assume that any law-abiding company will provide employment contracts including those clauses and (once agreed) the signature of both you and the company.
The entire hierarchy needs to be loaded in order to understand the full contract.For example, if there is a dispute, the lawyers who examine a contract will check what the law prescribes, perhaps by looking at a sample contract provided by the legislating body. The parentClass is that sample in the problem.
We only need one object instance. For example you won't get two employment contracts, one for the basic stuff and another with more information. You will receive and sign a single document.
Finally, in my analog, any employment contract (no matter how it is phrased) will be acceptable to any agency that asks you to prove your relationship to the company that employs you (assuming it is legal and valid by containing the legally prescribed clauses and appropriate signatures).
When you first load a class, all its ancestors are also loaded recursively.
When you instantiate an object you won't instantiate an additional instance of its parent. However, the object you just instantiated is itself also an instance of the parent.
This question already has answers here:
Java Multiple Inheritance
(17 answers)
Closed 7 years ago.
For eg:
Case 1: Does every Java class we create will extend Object class and if so then how come we an able to extend one more class to our class may be silly question just got it in mind i am posting this question
Pretty simple:
The hierarchy of java-classes is tree-like, with Object as root. If a class doesn't extend any other class it directly extends Object by default. So what about classes that extend some other class, like class A extends B. Now A extends B and Object. But this is not multiple inheritance. A extends B, thus A aswell extends any superclass of B, including Object. Just imagine the inheritance this way:
Object
/ | \
B ... SomeObject
|
A
Yes every class extends Object. However, Object is not necessarily the direct superclass. If a class Child extends Parent, then Child's direct superclass is Parent. In this case, the class hierarchy is:
Child < Parent < Object
So there is no multiple inheritance for Child. Object is inherited transitively by its direct superclass Parent.
No offense, but your english makes your question very difficult to read. I think I understood it though. Multiple inheritance is not the contrary of inheriting only from one class. You can inherit from several classes and still not have multiple inheritance.
For example, C inherit from A and B if A extends B, B extends C. However, the inheritance is a linear chain here, whereas multiple inheritance allows for trees, for example A extends B, A extends C. This is different, as you see. In java, you can inherit from as many classes as you like by transitivity but directly extend only one class.
Multiple inheritance is when you try to inherit more than a class at the same time,
I mean like
class Foo extends Faa, Fii {
}
that is not posible in Java but we can have this
class Faa{
}
class Fii extends Faa{
}
class Foo extends Fii{
}
that is not the same, in that case we have 2 parents (i mean Fii because we are extending from Fii and Faa because Fii extends from it)
If every class in Java implicitly extends Object class and multiple inheritance is not possible in Java then how do we even extend any class?
If you extend a class A that class in turn extends Object, so B extends A implicitly also extends Object.
"Java doesn't have multiple inheritance" means that you can't have two different parents, not that your parent can't have a parent.
C++ is an example of a language that lets you do multiple inheritance: http://www.learncpp.com/cpp-tutorial/117-multiple-inheritance/
Multiple inheritance looks like this:
class Teacher: public Person, public Employee
which means 'Teacher extends Person and Employee, inheriting its fields and methods'.
Instead of multiple inheritance, you're expected to create and implement interfaces to represent all the behaviours (or contracts if you prefer) your object supports. Java uses this for interfaces like Closeable and Serializable.
Multiple Inheritance is the concept of a single class inheriting from two or more super classes. If a class inherits from a super class and if that super class inherits from another super class it does NOT qualify as Multiple Inheritance. It is still Single Inheritance.
once u create object of sub class the object hierachy would be create on order of
objectclaass–>superclass—>subclass;
It is true that every class in Java inherits from the Object class – either indirectly or directly.
so in this case the sub class indirectly inherits object class.
Every Class that dosn't extends any other class it extends Object class.
if you extends anther class example extends Vector class
look to the hierarchy of class Vector you will end with a simple class that dosn't extends any anther class which explicitly extends Object.
and Any class extends anther class it explicitly extends all class that the parent class extends.
There is no multiple inheritance in Java, but there is class hierarchy. Inheritance in Java is transitive: if class A extends Object and class B extends A, than by transitivity A extends Object.
I have confusion in java inheritance. As I studied Java does not support Multiple Inheritance. So that it does not have diamond problem of inheritance at all.
But, every class of Java inherits Object class by default, and if we extend a class then there are two inherited classes first is Object and second is our inherited class. As I know if any class inherits two or more classes, its known as Multiple Inheritance. It shows that java supports multiple inheritance because its inheriting two classes at same time.
Then why its said that java does not support multiple inheritance and is there any possibility to have diamond problem in java?
Since all classes extend Object, the base class you're extending is by definition already extending Object. Your class doesn't need to add Object itself since it already exists in the hierarchy.
That means, Object will still only exist once in your hierarchy as the very root, so no "diamond".
See this
OBJECT CLASS
|
|
CLASS A{} //Class A extends class Object
|
|
CLASS B{} //Class B extends class A
|
|
CLASS C{}//Class C extends class B
Since every Class is inherited from Object class it is not in the case When you inherit from other class.Thus the object class will become super or the root class for all other inherited classes.
So whats the problem?
But, every class of Java inherits Object class by default, and if we extend a class then there are two inherited classes first is Object and second is our inherited class
That's partially correct.
If you extend a class explicitely, then it won't extend Object class.
if you have a class
class A
{
}
then, compiler will change it into
class A extends Object
{
}
But, if you extends a class explicitely, as following,
class A extends AnotherClass
{
}
compiler won't add anything now, hence No multiple inheritance.
You have misunderstood the concept of Class extending Object in case of Inheritance.
Only the top level class in the inheritance hierarchy, extends from Object class, and rest of the class lower in the hierarchy, extend the immediate super class. Thus they have all the methods of Object class through this hierarchy of inheritance, and there is no multiple inheritance involved.
public class A { // Extends from `Object` class
}
class B extends A { // Extends from `A`
}
class C extends B { // Extends from `B`
}
So, there will be no diamond problem in the hierarchy.
Java supports only syntactical multiple inheritance. Java does not
supports implementation of multiple inheritance.
Some people says java supports multiple inheritance through interfaces but it's not correct here the explanation:
inheritance ::
Getting the properties from one class object to another class object:
Class A{}
Class B extends A {}
Here an object of class B getting the properties(methods/functions/ & data members/class variables)
of class A.
Why java does not supports multiple inheritance using classes:
Class A{}
Class B{}
Class C extends A,B{}
X--this statement causes error because Class A getting object of object class from both sides A and B...
Every java class by default extending Object of object class and Object of object class is the root object means super class for all classes.
But here Class C having two super classes of object so giving error means java does not support multiple inheritance by using classes.
Is java supports multiple inheritance using Interfaces:
Because of this interface concept only few of us saying that java supports multiple inheritance but it is wrong.
Here the explanation::
interface A{}
interface B{}
interface C implements A , B{}
(or)
interface A{}
interface B{}
Class C implements A , B{}
Here its look like multiple inheritance but inheritance means getting the properties from one class object to another class object.
Here in interface concept we are not at all getting any properties rather we are implementing the unimplemented methods of interface in class.
So inheritance and intefaces are quite opposite.......
So finally java supports only syntax of multiple inheritance does not supports implementation of multiple inheritance.
Inheritance is like debit and interface is like credit but interface has its own importance in other concepts like server side programming.
Not exactly in Java you can only inherit from 1 distinct class at a time. That distinct class might inherit from another class however you don't have a single class inheriting from multiple distinct classes...
You can have many ancestors but only one parent. Here ancestors mean Object class where as parent mean the class which you are extending.
By specifying a class to inherit you override the default extends Object. So only when you don't specify a class to inherit does a class extend Object.
The class you extend from already extends from Object. When you extend from the new class, you in effect stop extending directly from Object, and instead inherit it via the new direct ancestor.
So it's not that you're extending from two different classes, it's that you're extending from a class that itself already extends from another class, namely the Object class.
Visually, multiple inheritance would be:
A Object
| |
C
But the situation you describe is actually:
Object
|
A
|
C