1

I have a problem of initializing List in constructor.

I am trying to assign parameters to variable "tr" and tr.getVertices() is a List.

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"

Where SimpleTriangle is a child class.

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;
}

3 Answers 3

5

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. You'll have to pass some List of Points to the constructor. The same is true for all other parameters of the constructor.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

@PaulBoddington my favourite computer talk of all time destroyallsoftware.com/talks/wat mentions it.
0

tr is a local variable which you want to instantiate. You need to instantiate an object before using its methods. Its like you are asking null to get a process done. And in-fact you can not even call it null as local variables in java are not auto initialized.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.