简体   繁体   English

我们可以为字符串调用Object类的toString()方法吗

[英]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: 但是,您可以模仿ObjecttoString()的输出(基本上只使用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.

相关问题 当我们在字符串上调用toString时,它会创建一个新对象吗? - Does toString create a new object when we call it on a String? 从 .class (Class<?> ) - Call Object's toString() method from .class (Class<?>) 为什么我们不能在方法之外使用类的对象来调用类的方法? - Why can't we call the method of the class using the class's object outside a method? 当我们覆盖toString()方法时,我们应该总是返回对象的字符串表示? - When we override the toString() method we should always return a string representation of the object? 我们可以使用类的引用来调用方法吗 - Can we call method using the reference of the class 我们可以在 null object 上调用任何方法吗? - can we call any method on null object? 为什么我们不能在PrintStream类的帮助下调用&#39;println()&#39;方法,其中out是这个类的对象? - Why we can't call 'println()' method with help of PrintStream class where out is object of this class? 我们可以将 String 称为包装器 class 吗? - Can we call String as a wrapper class? 如果类未提供该方法的实现,为什么类对象可以调用toString方法? - Why can class objects call the toString method if the class does not provide an implementation for the method? 试图在不同的Java类中调用toString方法 - trying to call a toString method in different Java Class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM