Why use setters in java instead of constructors? [duplicate]

Because you can change the value later for the same instance. For example, let’s assume a person with the following class: public class Person { String firstName; String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } Imagine there is … Read more

writing a constructor in java

You need to add instance variables for the four fields, then use these in your code. So in the constructor you would be setting the values for these instance variables (these values will be sent to the constructor generally from another class). private String description; private String dept; private int units; private double price; public … Read more

I need help making a java constructor that akes a string and initilizes the value var with appropriate in [closed]

Firstly if you want to equal “value” TO “a”, you must write: this.value = a; in Java (and a lot of programming languages), you must write variable that you change before equal mark. Second, if you will make “value” Integer. You must change it to int first: try { this.value = Integer.parseInt(a); } catch (NumberFormatException … Read more