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 ...
In a subclass, toString() can call the superclass toString() method using super. toString() and then add on its own attributes. In the following code, the Person class overrides the Object toString() method and the Student class overrides the Person toString() method.
super keyword is used to call parent class methods in case of inheritance. Every class is the child of Object class in java and one of its non-final methods is toString() . So super. toString() calls Object class method toSting() .
Every class in Java inherits the default implementation of the toString method.
Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With