Search code examples
javaabstract-classsubclasssuperclass

It is said that when we create an object of a sub-class automatically the objects of its super-classes get created. is it true?


it is said that when we create an object of a sub-class automatically the objects of its super-classes get created. is it true ? if yes then what if the super class is an abstract class.


Solution

  • No, that's not true. An object has only one type: the class that you instantiated. The object will also contain all the fields of the superclass, and it will be possible to call all the methods of the superclasses (that have not been overridden) on the object, but it is still only one object.

    For example, say you have:

    class A {
        int i;
    }
    
    class B extends A {
        int j;
    }
    

    If you instantiate new B(), you get one object that has storage for two fields, i and j.