Java Object Creation of Inherited Class
In Java, being an object-oriented language, objects inside a class is created with help of constructors. When it comes down to inheritance in Java we are basically dealing with deriving a class from another class. Now let us understand inheritance a step deeper so when a particular class inherits a class we do have a keyword that we use in order to refer to parent constructor via super keyword.
It is used as a suffix followed by the “.” operator in constructor/s in a class. This property of parent class(super class) also gets initiated well before child class(sub class) inherits and uses them.
Note: It is mandatory that when an object is created, the constructor is for sure called but it is not mandatory when a constructor is called object creation is mandatory.
We already have seen above when we created an object of a subclass, the constructor of the same class is called, if not made the default constructor is called while we called superclass constructor without creating an object of class inside subclass via keyword.
In inheritance, subclass acquires super class properties. An important point to note is, when a subclass object is created, a separate object of a superclass object will not be created. Only a subclass object is created that has superclass variables. This situation is different from a normal assumption that a constructor call means an object of the class is created, so we can’t blindly say that whenever a class constructor is executed, the object of that class is created or not.
Super class constructor Super class object hashcode :1149319664 Apple Subclass constructor invoked Sub class object hashcode :1149319664 1149319664 1149319664 Apple Apple
Output Explanation: As we can see that both superclass(Fruit) object hashcode and subclass(Apple) object hashcode are same, so only one object is created. This object is of class Apple(subclass) as when we try to print the name of the class in which object is created, it is printing Apple which is a subclass.
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Please Login to comment...