0
Getter and setter
Is it possible to use the Setter method only in java like this code? public class GettersAndSetters { public static void main(String[] args) { TestSetter setter2 =Â new TestSetter(); Â setter2.setNumber(10);Â System.out.println(num); } } public class TestSetter { Â Â Â Â private int number; Â Â Â Â public void setNumber(int num) { Â Â Â Â Â Â Â Â this.number = num; Â Â Â Â } }
2 Answers
+ 2
System.out.println(num); // error
This is where the getter would be used.
System.out.println(setter2.getNumber());
You can get and set the variable if it were public or package protected, without the getters/setters.
But just keep it private for encapsulation.
But yes, if you don't need to get the variable from an outside class, then you don't need a getter.
0
Thank you