• 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

Dan's Mock

 
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why the below piece of code prints R.printS1,S.printS2 ?
class R {
private void printS1(){System.out.print("R.printS1 ");}
protected void printS2() {System.out.print("R.printS2 ");}
protected void printS1S2(){printS1();printS2();}
}
class S extends R {
private void printS1(){System.out.print("S.printS1 ");}
protected void printS2(){System.out.print("S.printS2 ");}
public static void main(String[] args) {
new S().printS1S2();
}
}
When is the subclass method is called and when the superclass method is called ? What difference will it make it it is like
R r = new S();
r.printS1S2();
and why ?
Thanks in advance.
 
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Salim
1. The printS1S2 method is declared only in the super-class R, so that method will be called whether the run-time type of the object is of class R or S.
2. printS1S2 calls a private method in R, printS1. Private methods are essentially final, and cannot be overridden or hidden. That means that regardless of whether the run-time type of the object is of class S or class R, printS1S2 will call printS1 in R.
3. printS2 is not private, and is overridden in S. If the run-time type of the object is S, S.printS2 is called, and if the run-time type of the object is R, R.printS2 is called. This is an example of overriding and polymorphism.

output:
R:R.printS1 R.printS2
R(S):R.printS1 S.printS2
S:R.printS1 S.printS2
 
reply
    Bookmark Topic Watch Topic
  • New Topic