[Logo]
Forums Register Login
Dynamic Method Dispatch, What happens at JVM level
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
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.
 


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
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.
Bras cause cancer. And tiny ads:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss


This thread has been viewed 680 times.

All times above are in ranch (not your local) time.
The current ranch time is
Jul 22, 2018 23:26:41.