简体   繁体   English

为什么对象类方法将类的实例作为其参数

[英]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.

相关问题 类实例中的方法是否在内存中占有一席之地? - Do methods in class instances take a place in memory? Java中的通用方法:“对象不带参数” - Generic Methods in Java: “Object does not take parameters” 不同类实例的链接方法和对象共享 - Chaining methods of different class instances and object sharing 为什么对象类中的方法受到保护? - Why The methods in Object Class Are Protected? 为什么Java中的Object类包含受保护的方法? - Why does the Object class in Java contain protected methods? 为什么 Object 类有方法 wait() 和 notify() 而 Class 类没有? - Why Object class has methods wait() and notify() and Class class does not have? 是否可以同时访问多个对象实例的类的静态方法? - Is it possible to access static methods of a class by multiple object instances simultaneously? 向Java类添加方法是否会增加其实例的内存使用量? - Does adding methods to a Java class boost the memory usage of its instances? 为什么在Java中调用容器类的方法而不是它的实例 - Why calling methods from container class instead of instances of it in Java 为什么 Java 将我的第二个实例的参数分配给一个类的两个实例? - Why is Java assigning the parameters of my second instance to both instances of a class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM