Win a copy of Spring Boot in Practice this week in the Spring forum!
  • 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic