• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overriding : why "Superclass" is printed?

 
Ramakrishnan Ponmudi
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class superclass {
private void method1() {
System.out.println("Superclass");
}

public void method2() {
method1();
}
}


class subclass extends superclass {
public void method1() {
System.out.println("Subclass");
}

public static void main(String args[]) {
subclass sub = new subclass();
sub.method2();
}
}
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are calling method2() on subclass object.
Since the subclass doesn't have any method called method2(), the method2() of super class is called. When the method2() makes a call to method1(), it is the method1() of the super class which is being called actually. That call won't invoke the method1() in the subclass.

On the otherhand, if you try to call the method1() from your main method, you can see Subclass being printed.
 
Arvind Sampath
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I observed this fact while trying to answer your question.

If the access modifier for method1() in SuperClass is changed to public,default or protected "Subclass" is printed. If the access modifier is private then "Superclass" is printed.

Can someone clarify this ?

Thanks!

Regards,
Arvind
 
Ramakrishnan Ponmudi
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if u remove private access specifier , then it display "Subclass"?
how is it happen?
can u clarify.

Originally posted by Mani Ram:
You are calling method2() on subclass object.
Since the subclass doesn't have any method called method2(), the method2() of super class is called. When the method2() makes a call to method1(), it is the method1() of the super class which is being called actually. That call won't invoke the method1() in the subclass.

On the otherhand, if you try to call the method1() from your main method, you can see Subclass being printed.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple: private methods aren't known in subclasses, and therefore consequently can't be overridden - they are just shadowed. With other words, private methods aren't polymorphic.
 
Arvind Sampath
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a Lot, Ilja !

You've made things clear.


Regards,
Arvind
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic