aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Access control Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Access control" Watch "Access control" New topic
Author

Access control

Donovan Yung
Greenhorn

Joined: Oct 06, 2000
Posts: 6
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

Joined: Nov 15, 2000
Posts: 58
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).]


Aniruddha
rahil qamar
Greenhorn

Joined: Nov 16, 2000
Posts: 8
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


rahil
asim wagan
Ranch Hand

Joined: Nov 14, 2000
Posts: 62
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Access control
 
Similar Threads
Inheritance and static methods
Question on Overriding
Difference between Hidden and overriden methods.
java.lang.ClassCastException: Parent
Problem -- Virtual Method Invocation