[英]can we call the toString() method of the Object class for a String
can we call the toString() method of the Object class for a String 我们可以为字符串调用Object类的toString()方法吗
String string = new String("Hello");
System.out.println(string);
for a string the overrided method is called in the String. 对于字符串,将在String中调用重写的方法。 Are there any way to call the toString() method of the Object class for a String 有什么方法可以为String调用Object类的toString()方法吗?
I want to print out the memory address for the String object 我想打印出String对象的内存地址
No, you can not call the overridden method. 不,您不能调用覆盖的方法。 However, you could mimic the output of the Object
's toString()
(which basically only uses the hashCode) as follows: 但是,您可以模仿Object
的toString()
的输出(基本上只使用hashCode),如下所示:
string.getClass().getName() + "@" + Integer.toHexString(string.hashCode())
*edit: As noticed by Taemyr in the comments, an even closer mimic, that does not use the hashCode
defined by String
, would be: * edit:正如Taemyr在评论中所注意到的,一个更接近的,不使用String
定义的hashCode
模仿是:
string.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(string))
不,为什么?..因为该方法被覆盖 ,所以基于对象类型 ,在运行时 , 总是调用String
类中的方法
No you can't, once a subclass overrides a parent's member (function or variable), you can't reach them from outside that class. 不,您不能,一旦子类覆盖了父级的成员(函数或变量),就无法从该类外部访问它们。 that is the whole principle of encapsulation and inheritance (child classes having different behaviour than parent). 这就是封装和继承的整体原理(子类的行为与父类不同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.