[英]Creating object in method parameters
When creating a method inside a class if you use the parameter: 如果使用参数在类内创建方法,则:
public String Method(ClassName NewObject){}
or in my example below: 或在下面的示例中:
public String EqualsTo(Deck aCard){}
will it create a new object of that class within that method? 它将在该方法中创建该类的新对象吗? If not anyone mind explaing what I is happening with that parameter?
如果没有人介意解释我使用该参数发生了什么?
NOTE: Disregard any minor syntax errors as I just constructed this to get my question across better so this is not a complete class. 注意:忽略任何较小的语法错误,因为我只是构造了此语法,以便更好地理解我的问题,所以这不是一个完整的类。
import java.util.Scanner;
import java.util.Random;
public class Deck {
private int suit;
private int rank;
private Random generator = new Random();
Scanner in = new Scanner(System.in);
//Default constructor
public Deck() {
suit = suit.random(4);
rank = rank.random(13);
}
public String EqualsTo(Deck aCard){}
}
Objects are created when you use the new
keyword. 使用
new
关键字时将创建对象。 On the other hand, when you declare a method as 另一方面,当您将方法声明为
public String EqualsTo(Deck aCard){}
it says that the EqualsTo()
method takes a Deck
reference as a parameter. 它说
EqualsTo()
方法将Deck
引用作为参数。 In order to use the method, you need to create a Deck
object and keep a reference to it. 为了使用该方法,您需要创建一个
Deck
对象并保留对其的引用。 Then you send the reference to the method. 然后,您将引用发送给该方法。
That parameter act as a place holder for that type of object. 该参数充当该类型对象的占位符。 It doesn't actually create it, the method signature says:
它实际上并没有创建它,方法签名说:
I'm an EqualsTo()
method and I take/require a Deck
type of instance/object as a parameter. 我是一个
EqualsTo()
方法,我将需要实例的Deck
类型/对象作为参数。
It return a String
as a result. 结果返回一个
String
。
By the way, I recommend using a boolean as the return type instead of a 'String' for an EqualsTo method. 顺便说一句,我建议为EqualsTo方法使用布尔值作为返回类型,而不是'String'。
Fundamental thing: Java is pass by value. 基本原理:Java是价值传递。
aCard
. aCard
。 Here's an example. 这是一个例子。
public class Test2 {
public int bla;
public static void main(String[] args) {
Test2 test = new Test2();
test.bla = 878;
test.doSome(test); // Calling Location
System.out.println(test.bla);
}
public void doSome(Test2 test) {
test.bla = 95;
}
}
NO 没有
public String EqualsTo(Deck aCard){}
Does not create a new object when it is called. 调用时不创建新对象。
Here is where the objects are created. 这是创建对象的地方。 Use case
用例
Deck deck1 = new Deck(); // NEW OBJECT CREATED
Deck deck2 = new Deck(); // NEW OBJECT CREATED
String result = deck1.EqualsTo(deck2); // NO NEW OBJECT CREATED,
// JUST PASSED REFERENCE OF EXISTING OBJECT
// (except the result of course, which is probably a new object)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.