• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Overriding & private modifier

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the below code snippet
It prints 1
But if f() is not private then it invokes the method in PolyC and prints 2
Since PolyC does not have g() method the inherited method from PolyB is invoked.Now it has to resolve the call to f().
My doubt is since it will call this.f() why is not calling f() method in polyC than private f() method in PolyB...I am confused ..Is it some thing to do with executing within the context



public class test {
public static void main(String args[]) {
PolyA ref1 = new PolyC();
PolyB ref2 = (PolyB)ref1;

System.out.println(ref2.g()); // This prints 1
// If f() is not private in PolyB, then prints 2
}
}

class PolyA {
private int f() { return 0; }
public int g() { return f(); }
}

class PolyB extends PolyA {
private int f() { return 1; }
public int g() { return f(); }
}

class PolyC extends PolyB {

public int f() { return 2; }
}
 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
when f() is declared private in PolyB, any redefinition of f() in a subclass(e.g. PolyC) is not considered to be overriding the private f(). So even though they look similar, java sees them as two different methods that have nothing in common.
 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the above code if f() is public in PolyB then PolyC has overridden f(). Since the method to be run is decided at runtime and the ref2 object points to PolyC so the PolyC.f() will be run.
 
I yam what I yam and that's all that I yam - the great philosopher Popeye. Tiny ad:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic