Help coderanch get a
new server
by contributing to the fundraiser
  • 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 & 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.
 
A sonic boom would certainly ruin a giant souffle. But this tiny ad would protect it:
We need your help - Coderanch server fundraiser
https://coderanch.com/t/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic