Reputation: 652
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?
Upvotes: 0
Views: 68
Reputation: 1502056
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";
}
Upvotes: 3