This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Welcome to the forum! The reason why the child class method is called is because when you do
polymorphism comes into effect. Everytime you access an instance method that is overridden, the version of the method which is called is the version defined in the type of the object, not the reference (and in this case the object is a child class object, so you end up calling the overriding version of the method.)
As to whether you can call the superclass version without modifying the child class code: Not when you are calling the method through a reference which is linked to a child class object. In order to call the overridden version you would need to use the super keyword in the child class code to achieve that.
I hope that helped.
All code in my posts, unless a source is explicitly mentioned, is my own.
Hi, first of all please remember that casting reference type only affects static methods and fields. Non Static instance method are not affected whether you apply any reference casting or not. Non static instance methods are called depending on the actual type of object and not reference and this thing is resolved at runtime only.
since at this statement: BobTest f = new Bob(); and that Bob extends BobTest
f is pointing to object of Bob and the method called in an instance method, so the method defined in Bob class is called.
In order to invoke the parent class method, you need to add statement super.toString(); in the sub class Bob toString() method.
Obstacles are the things we see when we take our eyes off our goals.
Joined: Dec 16, 2008
Just to add to what Robin said that you have to consider access levels. Casting can affect instance methods as well. For example, let's say you have a class A with a private instance method x(), and a subclass B with a public instance method x(). A.x() and B.x() are different instance methods (B.x() doesn't override A.x() because A.x() is private and thus it is not inherited by B.) However, if you have an reference of type B b, you can call b.x(). But if you cast the reference to A, then you can't call the x() method: ((A) b).x().