调用父类方法而不更改代码 [英] Invoking parent class method without changing code

查看:79
本文介绍了调用父类方法而不更改代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码片段.

class X {
    public String toString() {
        return "Hi";
    }
}

public class Main {
    public static void main(String[] args) {
        Object obj = new X();
        System.out.println(obj.toString());
    }
}

如何在不更改代码的情况下立即在Object类中调用toString()?还是我问不可能?

How do I invoke the toString() inside Object class now, without changing the code? Or what I ask is not possible?

推荐答案

从外部看,您不能-这样做会违反封装. (想象一下toString()实际上是一种改变对象状态的方法,并且子类想要强制执行一些约束-您不应该跳过这些约束.)您可以从X本身内部进行操作,例如

From the outside, you can't - that would violate encapsulation. (Imagine toString() were really a method to mutate the state of the object, and the subclass wanted to enforce some constraints - you shouldn't be able to skip those constraints.) You can do it from within X itself, e.g.

public String toString() {
    return super.toString() + "Hi";
}

这篇关于调用父类方法而不更改代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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