| Author |
overriding : why "Superclass" is printed?
|
Ramakrishnan Ponmudi
Ranch Hand
Joined: Apr 20, 2004
Posts: 72
|
|
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
Joined: Mar 11, 2002
Posts: 1140
|
|
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.
|
Mani
Quaerendo Invenietis
|
 |
Arvind Sampath
Ranch Hand
Joined: May 11, 2005
Posts: 144
|
|
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
Joined: Apr 20, 2004
Posts: 72
|
|
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
Joined: Jul 11, 2001
Posts: 14112
|
|
|
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.
|
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
|
 |
Arvind Sampath
Ranch Hand
Joined: May 11, 2005
Posts: 144
|
|
Thanks a Lot, Ilja ! You've made things clear. Regards, Arvind
|
 |
 |
|
|
subject: overriding : why "Superclass" is printed?
|
|
|