• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

access modifiers

 
keith barron
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 29
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1492
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you for your clear explanation Manfred!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic