• Post Reply Bookmark Topic Watch Topic
  • New Topic

Dynamic Method Dispatch, What happens at JVM level  RSS feed

 
Pratibha Malhotra
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
If i have a attribute both in sub and super class
superClass obj = new subClass();
obj.callme();
call callme() present in subclass
where as
System.out.println(obj.counter); prints value assigned in super class

whyyyyyyyy???


I want to know what happens at JVM level.
Is it coz attribute is attached outside Method Area in JVM and is attached to class declaration

plz Help





class testInheritance
{
public static void main (String s[])
{ superClass obj = new subClass();
obj.callme();
System.out.println(obj.counter);
}

}

class superClass
{ int counter = 0;
void callme()
{System.out.println("Super class");
}
}


class subClass extends superClass
{ int counter = 10;
void callme()
{System.out.println("Sub class");
}
}


bash-3.00$ java testInheritance
Sub class
0
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simple answer is just "because that's the way it is". Fields are not polymorphic. If you define a field in a subclass that has the same name as a field in a superclass, it is said to "hide" the superclass field, and all sorts of bad, confusing things happen. There's no reason to do this; the subclass can simply assign a new value to the existing superclass field.

This is hardly an advanced topic; moving to Java in General (Beginner) for any further discussion.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!