• 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

overridding doubt

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class a{
public void show(){
System.out.println("parent");
}
}

public class override extends a{
protected void show(){
System.out.println("child");
}

public static void main(String[] args) {
a a = new override();
a.show();
}
}
the program is not compiled.
it shows that subclass overridden method can not reduce the visibility of parent class method.
can anyone explain reason for this.

but the second program compiles fine
class a{
protected void show(){
System.out.println("parent");
}
}

public class override extends a{
public void show(){
System.out.println("child");
}

public static void main(String[] args) {
a a = new override();
a.show();
}
}
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look at the code below


aMethod is overridden
if reducing the visibility was allowed how would dynamic method resolution work.


This could would compile but during runtime give a error (if reducing the visibility was allowed on methods). So i guess they have not allowed such stuff.

correct me if i am wrong.
 
Ranch Hand
Posts: 153
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1)private->package->protected->public

2)In first case you are trying to narrow the accessibility of the method.

3)From protected you can only change it to public in the overriding method.

4)See rules for overriding in any java book.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic