[英]Why does the object class methods take instances of class as their parameters
To explain my question, in below code why do I have to pass object/instance of a class just to see how toString method is being overridden and why does the toString method, doesn't have parameter of type class to accept that object ? 为了解释我的问题,在下面的代码中,为什么我必须传递类的对象/实例才能看到toString方法如何被覆盖,以及为什么toString方法没有类型类型的参数来接受该对象?
Class Teacher
{
public String toString()
{
return("Hello")
}
}
Class TestTeacher
{
public static void main(String []arr)
{
Teacher obj = new Teacher();
System.out.println(obj);
}
}
why do I have to pass object/instance of a class just to see how toString method is being overridden
为什么我必须传递类的对象/实例只是为了查看toString方法如何被覆盖
You do not need to pass the object to the toString
method, you can just call 您不需要将对象传递给
toString
方法,只需调用
Teacher obj = new Teacher();
String output = obj.toString();
System.out.println(output);
and why does the toString method have an parameter of type class to accept that object ?
为什么toString方法具有类型为class的参数来接受该对象?
It has not. 它没有。 I think you are confused because you call the normal println function with the object.
我认为您很困惑,因为您使用该对象调用了普通的println函数。 In turn internally the
toString
function is called to be able to print something to the standard output. 进而在内部调用
toString
函数,以便能够将某些内容打印到标准输出中。 So the object here is not the parameter of toString
but is the parameter of the println
function. 因此,这里的对象不是
toString
的参数,而是println
函数的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.