• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Access control

 
Donovan Yung
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm testing myself on some concepts and came across this problem:
public class Parent {
private void print() {
System.out.println("In Parent");
}
public static void main(String[] args) {
Parent p1 = new Parent();
p1.print();
p1 = new Child();
p1.print();
Child c1 = new Child();
c1.print();
}
}
class Child extends Parent {
public void print() {
System.out.println("In Child");
}
}
When I run it, the output is:
In Parent
In Parent
In Child

Why does the second p1.print() give "In Parent" instead of "In Child"? Does this mean the print() method in Child class is shadowing the parent's print() like with varibles?
 
Aniruddha Mukhopadhyay
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Donovan
If you remove the access modifier from print() in Parent (i.e. make it "friendly"), it will print in Parent, in Child, in Child.
I think it is because private methods are not visible to subclasses, it is not a case of overloading in the way you have written in your code. Instead it is treated like just another method.
Thanks for putting this problem in Javaranch - I may not have known about this peculiarity otherwise!
Aniruddha
[This message has been edited by aniruddha mukhopadhyay (edited November 16, 2000).]
 
rahil qamar
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Donovan
This is because the access modifier in the Parent class is "private" which prevents overridding. Change the modifier in the Parent class to "public", or "protected", or the default modifier and you will see that the "print(") method of the Child class being called.
Rahil
 
asim wagan
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As up there you have declaed p1 as parent first and then refered to its child so it will see it in the perspective of the parent. but individualy declaring a child will cause child to print it's method not it's parent's.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic