• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Dynamic Method Dispatch, What happens at JVM level

 
Ranch Hand
Posts: 199
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author and iconoclast
Posts: 24204
44
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
She'll be back. I'm just gonna wait here. With this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic