It's not a secret anymore!
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Access control" Watch "Access control" New topic

Access control

Donovan Yung

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 = new Child();
Child c1 = new Child();
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: 59
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!
[This message has been edited by aniruddha mukhopadhyay (edited November 16, 2000).]

rahil qamar

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

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:
subject: Access control
It's not a secret anymore!