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

后端 未结 5 1326
無奈伤痛
無奈伤痛 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: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.

提交回复
热议问题