Reputation: 3293
I have this code:
public class Superclass {
public void print() {
System.out.println("super");
}
}
public class Subclass extends Superclass {
public void print() {
System.out.println("sub");
}
}
And then this:
Subclass obj4 = new Subclass();
((Superclass) obj4).print();
I would think that the above print statement prints "super," since it is cast to Superclass, but this is not the case - it prints "sub". Why is this?
Upvotes: 1
Views: 247
Reputation: 1709
If you are overriding a method from a superclass you need to include the @Override notation in your sub class.
Also if you want to use the print() method of the super class,in your subclass's print() method you can use super.print();
im 100% that will work.
Upvotes: 0
Reputation: 328
Typecasting an object doesn't change the object itself. It basically helps you to access the fields / methods which are part of the contract of the class you typecast an object reference to. Let's say your Subclass had this definition:
public class Subclass extends Superclass {
public void print ( ) {
System.out.println ("sub");
}
public void subClassMethod()
{
//do something
}
}
And you create an object of type Subclass but hold the reference using a Superclass variable:
Superclass obj4 = new Subclass ();
Now obj4 gives you access only to the contract for Superclass so you cannot call obj4.subClassMethod() which will give you a compile time error.
In this case you will typecast it to Subclass to get access to the subClassMethod:
((Subclass)obj4).subClassMethod()
Upvotes: 1
Reputation: 4241
Because you are implicitly overriding the method in your subclass.
If you have used C# before, this might be confusing, because Java does not need an override keyword to override methods. Java automatically overrides methods with the same signature.
You might see the @Override
annotation on methods, but that's just a safeguard to ensure that you're actually overriding something (it prevents typos and such); it does not actually impact your program itself.
Upvotes: 1
Reputation: 3325
This is because you didn't call super.print(). By default, subclass's method overrides superclass's one, no matter what casting you make
public class Subclass extends Superclass {
public void print () {
super.print();
System.out.println ("sub");
}
}
Upvotes: 1
Reputation: 63094
The upcasting of the type doesn't make any different. Which toString()
to call is determined by the runtime type of the instance, not the reference.
Since Subclass
overrode Superclass
's toString, invoking any Subclass
instance will always resolve to Subclass
's toString.
Object obj = new Subclass();
obj.toString(); // will still return "sub"
Upvotes: 4