简体   繁体   中英

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

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.

You can just add another method to call the super string. Something like:

public string getSuperString(){
    return super.toString();
}

You can either

  • Add a method to A or B which you call instead.

     // to A public String AtoString() { return toString(); } // OR to B public String AtoString() { return super.toString(); }
  • Inline the code of A.toString() to where it is "called"

     // inlined A.toString() String ret = "I am A"; System.out.println( ret );

Both these options suggest a poor design in your classes, however sometimes you have existing classes you can only change in limited ways.

这是不可能的,因为 A 的 toString() 被 B 覆盖(我猜,你的意思是“B 类扩展 A”)。

In your code it is not possible, in case B extends A

public class TestSuper {
    public static class A {
        @Override
        public String toString() { return "I am A"; }
    }
    public static class B {
        @Override
        public String toString() { return "I am B"; }
    }
    public static void main(String[] args) {
        B b = new B();
        System.out.println( b ); // --> I am B
        A a = (A)b;
        System.out.println( a ); 
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM