existantial question
if i have a class hierarchy like:
public class TestSuper {
public static class A {
@Override
public String toString() { return "I am A"; }
}
public static class B extends A {
@Override
public String toString() { return "I am B"; }
}
public static void main(String[] args) {
Object o = new B();
System.out.println( o ); // --> I am B
// ?????? // --> I am A
}
}
From the main method, is it possible to call the toString of A when the instance is of type B ???
of course, something like o.super.toString() doesn’t compile …
You can’t, and very deliberately so: it would break encapsulation.
Suppose you had a class which used a method to validate input by some business rules, and then call the superclass method. If the caller could just ignore the override, it would make the class pretty much pointless.
If you find yourself needing to do this, revisit your design.