• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

overriding method

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can anyone pls explain why the foll piece of code prints 1 for sup1.methodA() instead of 0?

class Superclass {
int x = 0;
int methodA()
{
return x;
}
}

class Subclass extends Superclass {
int x = 1;
int methodA()
{
return x;
}
}

class Q30 {
public static void main(String[] args)
{
Subclass sub = new Subclass();
System.out.println("sub.methodA()= " + sub.methodA());

Superclass sup = new Superclass();
System.out.println("sup.methodA()=" + sup.methodA());

Superclass sup1 = new Subclass();
System.out.println("sup1.methodA()=" + sup1.methodA() + process(sup1));
}

static int process(Superclass obj)
{
return obj.x;
}
}
 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
because of polymorphysm sup1.methodA() return 1,since variables are shadowed process(sup1) returns 0
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you created sup1 you gave it a type of the superclass. The JVM then went out and created all of the fields (instance variables) for sup1 from the superclass.
When you initialized sup1 you put an object of the subclass in it. Since methods are resolved at runtime (late binding) the methods of the subclass are used. That is how overriding is accomplished.
 
suneeta prabhu
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jeena and Cindy. I got it now.
 
suneeta prabhu
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jeena and Cindy.
 
and POOF! You're gone! But look, this tiny ad is still here:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic