简体   繁体   English

Java。 在构造函数中初始化列表

[英]Java. Initializing List in constructor

I have a problem of initializing List in constructor. 我在构造函数中初始化List时遇到问题。

I am trying to assign parameters to variable "tr" and tr.getVertices() is a List. 我正在尝试将参数分配给变量“ tr”,tr.getVertices()是一个列表。

SimpleTriangle tr = new SimpleTriangle(tr.getVertices(), tr.getColour(), tr.getThickness(), ShapeType.TRIANGLE);
trList.add(tr);

It higlights tr.getVertices() and says "Variable tr might not been initialized" 它高亮显示tr.getVertices()并说“变量tr可能未初始化”

Where SimpleTriangle is a child class. 其中SimpleTriangle是子类。

public SimpleTriangle(List<Point> vertices, Color colour, int thickness, ShapeType shapeType) {
super(vertices, colour, thickness, shapeType); }

and parent class has method 父类有方法

    public List<Point> getVertices() {
    return vertices;
}

You are trying to call a method on a variable you haven't initialized yet: 您正在尝试对尚未初始化的变量调用方法:

//              v--this variable        v--is not yet initialized here
SimpleTriangle tr = new SimpleTriangle(tr.getVertices(), tr.getColour(), tr.getThickness(), ShapeType.TRIANGLE);

You are trying to initialize a SimpleTriangle with it's own vertices, which doesn't make any sense. 您正在尝试使用自己的顶点来初始化SimpleTriangle ,这没有任何意义。 You'll have to pass some List of Point s to the constructor. 您必须将Point的一些List传递给构造函数。 The same is true for all other parameters of the constructor. 构造函数的所有其他参数也是如此。

The error is correct, you cannot use a variable before it has been initialised. 错误是正确的,您不能在变量初始化之前使用它。

You need to provide it real values, not ones which will only make sense in the future. 您需要提供真实的价值,而不是仅在将来有意义的价值。

Note: Ruby does allow you to do what you suggest and could be considered a bug in the design of the language. 注意:Ruby确实允许您做您建议的事情,并且可能被认为是该语言设计中的错误。

tr is a local variable which you want to instantiate. tr是要实例化的局部变量。 You need to instantiate an object before using its methods. 您需要在使用对象的方法之前实例化该对象。 Its like you are asking null to get a process done. 就像您要让null完成流程一样。 And in-fact you can not even call it null as local variables in java are not auto initialized. 实际上,您甚至不能将其称为null,因为java中的局部变量不会自动初始化。

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

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