如何从派生类外部调用超级方法(即:toString()) [英] How to call a super method (ie: toString()) from outside a derived class

查看:164
本文介绍了如何从派生类外部调用超级方法(即:toString())的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现实问题

如果我有类层次结构:

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

当实例是B类型时,调用toString A ???

From the main method, is it possible to call the toString of A when the instance is of type B ???

当然,像o.super.toString()这样的东西不能编译...

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.

这篇关于如何从派生类外部调用超级方法(即:toString())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆