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

9th Aug 2017, 2:12 PM
Sibusiso Mbambo
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.
9th Aug 2017, 2:53 PM
Rrestoring faith
Rrestoring faith - avatar
0
Thank you
9th Aug 2017, 2:54 PM
Sibusiso Mbambo