• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamic Method Dispatch, What happens at JVM level

 
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
Marshal
Pie
Posts: 24211
35
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.
 
Pratibha Malhotra
Ranch Hand
Posts: 199
  • 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.


if field in subclass hides field in superclass then why
System.out.println(obj.counter);
prints value assigned in super class
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because "obj" is a reference to the superclass type. If println(obj.counter) printed the subclass value, then that would mean the variable was being chosen based on the runtime type of obj; but it's not, it's being chosen based on the compile-time type. In other words, as I said, fields are not polymorphic. The "hiding" occurs only if you have a reference of subclass type.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic