[Solved] I don’t understand this common java principle [duplicate]


Consider Apollo’s comment and google it.

This is not only a java principle but a generall programming principle.

You’re creating a new Answer Object.

Let’s look at this example:

public class Answer{ // The class

  private String answer; // internal variable only visible for the class

  public Answer(String answer){ // This is a constructor
    this.answer = answer; // Here we assign the String we gave this object to an internal variable
  }

  public void setAnswer(String answer){ // Setter
    this.answer = answer;
  }

  public String getAnswer(){ // Getter
    return answer;
  }
}

So now you have a class/Object named Answer.
When you now want to use it you need to create a new Object.
This is done over the constructor of a class. ( Constructor = basically a definition of what you need to create the Object )

First you declare what Object you want your variable to be, then you give the variable a name you can use it under.

That looks like this:

Answer variableName

But this will not create a new object.
To create it we need to give the keyword new in combination of a Constructor of the object we want to create.

As we defined a constructor that needs a String to create this object we need to call it like this:

new Answer("the string");

If we combine those two we finally have our usable new variable of a new create Answer

Answer yourVariable = new Answer("the string");

solved I don’t understand this common java principle [duplicate]