开发者

Invoking parent class method without changing code

开发者 https://www.devze.com 2023-03-08 07:29 出处:网络
Consider the following code snippet below. class X { public String toString() { return \"Hi\"; } 开发者_如何学编程}

Consider the following code snippet below.

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());
    }
}

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


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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消