Win a copy of Microservices Testing (Live Project) 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

Overrding

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class SuperClass {
public static void main(String ar[])
{
System.out.println(new SubClass().g());
}
public int g()
{
return f();
}
private int f()
{
return 1;
}
}
class SubClass extends SuperClass{
public int f()
{
return 2;
}
}
I cannot understand why does this code produces an output of 1?
Can anyone explain?
 
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
SubClass is not having method g(), it will implicitly call the SuperClass g(), HTH.
-Arun
 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
HI
Here the call new SubClass().g() invokes the inherited method g() from SuperClass (as g() is not present in SubClass) and then in the method
g() there is a call to f() in the statement return f()...now since f() is private in the SuperClass so the method f() of SuperClass is invoked not the one in SubClass( as u may think that u r working on the SubClass object)..Also,
u should know that private and static methods r never overridden...
In this code the method public int f() {}
is not overriding the private int f(){} in SubClass..
THats why the answer is 1.
Hope this helps
Swapna
 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Another the to explain:
member variales are static-linked as well as the private methods,it is said that when using "new" to construct an instance,the member variables and preivate methods are definite.but other methods not,it is linked at runtime
in this case,method g() in Super already knows where to invoke the f(),because f() is private.it is already linked to the g() method as well as the instance.
so is clear
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic