我是一个 Java 新手,阅读了一些有关在 Java OOP 中传递类和返回类的问题,但不幸的是找不到答案。所以我提出了我的问题,希望你们能自由地分享你们的想法。
假设我们有一个关于组合的代码块“一个案例在类“维度”中定义了一些维度:
public class Case {
private String model;
private Dimensions dimensions;
public Case(String model, Dimensions dimensions) { // line AAA
this.model = model;
this.dimensions = dimensions;
}
public Dimensions getDimensions() {
return dimensions; //line BBB
问题 1:在 AAA 行,我们将“Dimensions dimensions”作为参数传递给构造函数,为什么不使用“new”关键字来实例对象
问题2:在BBB行,我们返回“dimensions”,为什么不用“return new Dimensions”来返回一个对象。在一些文章中,我看到他们使用。那么,哪些情况我们应该使用"new",哪些情况不应该使用?
谢谢。
最佳答案
Question1: at line AAA, we pass "Dimensions dimensions" into the constructor as a parameter, why don't use "new" keyword to instance object
通常,您会传入一个已经创建的对象,如下所示:
String model = "myModel";
Dimensions dim = new Dimensions();
Case case = new Case(model, dim);
所以现在 case 对象的维度变量将包含对通过构造函数传递的维度对象的引用。
Question2: at line BBB, we return "dimensions", why don't use "return new Dimensions" to return an object. In some articles, I see they use. SO which situation we should use "new", and which we should not?
getDimensions()
方法是一个 getter 方法,意味着我们要获取 this
对象维度的值。所以返回一个新的维度对象没有意义。要获取上面创建的 case
对象的维度,您可以使用:
Dimensions caseDimension = case.getDimensions();
关于java - 传递和返回没有 "new"关键字的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53467582/