Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a super method (ie: toString()) from outside a derived class

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 ...

like image 222
fedevo Avatar asked Jun 17 '11 13:06

fedevo


People also ask

How do you call the toString method of super class?

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.

What is super toString ()?

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() .

Is toString inherited by all classes?

Every class in Java inherits the default implementation of the toString method.

Why should you override 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.


1 Answers

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.

like image 158
Jon Skeet Avatar answered Sep 18 '22 00:09

Jon Skeet