Invoking parent class method without changing code
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";
}
精彩评论