-1

I have confusion in object life cycle. If parent class reference pointing to the child class object and method is overridden. For example

class Parent {
     public void display(){
           System.out.println("i am from Parent");
     }
}

class Child extends Parent {
     public void method1() { }

     public void display(){
           System.out.println("i am from Child class");
     }
}

Now if I create the in main class

Parent p = new Child();

Is my understanding object life cycle is proper or not? If not please guide me.

  1. new Child() constructor get called

  2. by super() method parent class constructor(default constructor) get called

  3. now according to object life cycle first constructor get called and concrete method that is display() method from parent class get stored in heap.

  4. after Child class constructor finish the execution and method1() and display() method get stored in heap memory.

Now if I call p.display() its going to execute child class display() method, but if you see both parent and child class display() method stored in heap memory.

If this behavior proper then what is the use of storing the display() method of parent in heap.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Girish
  • 107
  • 3
  • 10
  • You can test all of your question easily. – Maroun Feb 02 '15 at 09:59
  • Both method's behaviour is different. They are not same. if you want to execute parent method its needs to be present – Yagnesh Agola Feb 02 '15 at 10:03
  • parent constructors are invoked before child constructors when you create an instance of child. – Prinz Km Feb 02 '15 at 10:06
  • 1
    Methods get stored in permgen space (Method area). But whether all of them are stored and when they are stored is *implementation* dependent. – TheLostMind Feb 02 '15 at 10:09
  • 1
    You are misunderstanding and mixing unrelated concepts, such as: object life cycle class loading (this one responsible for loading type definitions and their methods); class constructor instance constructor; objects methods; etc – Miguel Gamboa Feb 02 '15 at 10:20

2 Answers2

0

You are right on bullet 1, 2 (super() will be implicitly first statement of your child constructor.). Method doesn't get stored on heap. It's only properties of an object and object itself gets stored on Heap. It's just the definition of class and methods stored in perm gen area which is separate from heap.

SMA
  • 36,381
  • 8
  • 49
  • 73
0

Its because you might need to call class display method from some other method in derived class by using super.basemethodname. . Also display might be overloaded in super so u can differentiate nd call the right method by passing right args

Bharat
  • 152
  • 1
  • 9