简体   繁体   English

在方法参数内创建构造函数

[英]creating a constructor inside a method parameter

 class Test {

  int a, b;

  Test (int i, int j){

  a = i;
  b = j;
  }
  boolean equalTo( Test o){

  if(o.a == a && o.b == b) return true; else return false; 

  }

  }

Im confused you can create an object of of constructor inside method parameter? 我很困惑,您可以在方法参数内创建构造函数的对象吗? I was reading a java textbook and boolean equalTo( Test o) they assigned Test value to o. 我正在阅读一本Java教科书和一个布尔equalTo(Test o),他们将Test值分配给了o。 My second question is, is there another time where u can put a class inside a method? 我的第二个问题是,您是否还有其他时间可以将类放入方法中?

When we define method, the parameters that the method accepts can be a primitive value or a reference to an object with certain classes. 当我们定义方法时,该方法接受的参数可以是原始值或对具有某些类的对象的引用。 Reference to an object is not creating an object. 引用对象不是在创建对象。 Every time you want to create an object of certain class, you would have to have the new keyword follow by class name and their constructor parameters. 每次您要创建某个类的对象时,都必须让new关键字后跟类名及其构造函数参数。

When you are making a method, you can accept any reference of any class in the parameters. 制作方法时,可以接受参数中任何类的任何引用。 You make a method that accept references of other classes when you want to access other class information of calling their methods. 当您要访问调用其方法的其他类信息时,可以创建一个接受其他类的引用的方法。

I would recommend to try this tutorial to get a better understanding of Object-Oriented Programming. 我建议尝试使用本教程,以更好地理解面向对象的编程。 https://www.w3schools.com/java/java_oop.asp https://www.w3schools.com/java/java_oop.asp

When you passed object with class Test to the method equalTo , every information of the passed object stays in the same location in virtual memory, only the reference is given to the method. 当您将带有类Test对象传递给方法equalTo ,传递的对象的每个信息都保留在虚拟内存中的同一位置,因此仅对该方法提供了引用。 With reference, we can access or manipulate the passed object without having the whole data structure being copied from the memory. 参考,我们可以访问或操纵传递的对象,而无需从内存复制整个数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM