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 ответов
+ 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