Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Inheritance quesiton

PremOct 10 2015 — edited Nov 22 2015

Hi, 

I am expecting output from following code as 10 But it gives output of 5. Can anybody tell me why this.id is returning parent class value? My understanding is by default you will have getId() which in thurn returns this.id.So when Ihave created  Child c=new Child() , it should look into child class to access that method and should return value of child class itself but it is returning parent class value. I m too much confused. Kindly guide me.

[code]

Class Parent{

private int id=5;

public int getId(){

  return this.id;

}

}

Class child extends Parent{

private int id=10;

public static void main(string []ar){

Child c = new Child();

System.out.println(c.getId());

}

}

[/code]

Comments

Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Dec 20 2015
Added on Oct 10 2015
5 comments
1,477 views