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

后端 未结 5 1327
無奈伤痛
無奈伤痛 2020-12-11 01:58

existantial question

if i have a class hierarchy like:

public class TestSuper {
    public static class A {
        @Override
        public String t         


        
相关标签:
5条回答
  • 2020-12-11 02:16

    It's not possible, because toString() of A is overriden by B (I guess, you meant "class B extends A").

    0 讨论(0)
  • 2020-12-11 02:19

    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.

    0 讨论(0)
  • 2020-12-11 02:27

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

    public string getSuperString(){
        return super.toString();
    }
    
    0 讨论(0)
  • 2020-12-11 02:31

    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 ); 
        }
    } 
    
    0 讨论(0)
  • 2020-12-11 02:32

    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.

    0 讨论(0)
提交回复
热议问题