File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes access modifiers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "access modifiers" Watch "access modifiers" New topic
Author

access modifiers

keith barron
Greenhorn

Joined: Apr 04, 2001
Posts: 6
why does the result change when the access modifier for Superclass::methodB changes from private to public?
public class Superclass {
public static void main(String[] args) {
System.out.println(new Subclass().methodA());
}
Superclass() {
System.out.println("SuperClass Constructor Executed");
}

private int methodB() {
System.out.println("methodB in Superclass");
return 9;
}

int methodA() {
System.out.println("methodA in Superclass");
return methodB();
}
}

class Subclass extends Superclass {
Subclass() {
System.out.println("SubClass Constructor Executed");
}

public int methodB() {
System.out.println("methodB in Subclass");
return 1;
}
}
Bala Arul
Greenhorn

Joined: Feb 09, 2001
Posts: 29
Hi Keith,
I hope that the following thread would help.
http://www.javaranch.com/ubb/Forum24/HTML/009073.html
Bala Arul
[This message has been edited by Bala Arul (edited April 04, 2001).]
keith barron
Greenhorn

Joined: Apr 04, 2001
Posts: 6
the example you referred to different in that the result does not change when the access modifiers for Parent::hello from private to public. that is really my question. i would like if you would compile and run the code, make the change to the access modifier in Superclass::methodB and see the result change.
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Keith,
The reason is that private methods can not be overridden because they can only be seen by the class itself not subclasses.
When you run the example with the method private the Superclass class can only see its own methodB which is the one that gets executed. Even though we are using a Subclass object with calling the method!
When you run the example with the method public you are allowing Subclass to override the method. Therefore, since we are using a Subclass object we actually run the overridden method found in Subclass class.
As Marcus Green stated in his online exam, "If you get a question like this on the exam consider yourself extemely unlucky"!
Manfred.
keith barron
Greenhorn

Joined: Apr 04, 2001
Posts: 6
thank you for your clear explanation Manfred!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: access modifiers
 
Similar Threads
problem regarding constructor
method call
Overriding
Jtips - mockexam #1
jtips 1, q26