Not at all. The JVM determines at runtime, based on the exact type of an object which method to invoke.
Your nice little casting does achieve nothing. Because you can't change the runtime type of a reference by casting!
One solution would be to have something like:
public String superToString() {
return super.toString();
}
inside such classes, and to invoke that method explicitly. Alternatively, the line that currently does that cast could be replaced with return super.toString()
of course.
But then, especially option 1 would only add "worse to bad". As in: the contract of toString()
is to return a string.
Simply never ever write toString()
methods that
- requires a lot of intensive work to happen or
- can throw an exception!
See How to use toString method in Java for some further thoughts.
Seriously: in any larger project, you have zero control when/how often/in which ways toString()
is called on your objects. You better make sure these calls return quickly, return reasonable information and never ever throw an exception.