In my opinion, there is only a syntax difference between parameterized constructors and setter function in JAVA. Both would be used to initialize the class variables with user-defined values.
In parameterized constructors, all the class variables can be initialized within one function (constructor) which is automatically invoked when a user creates an object of that class.
On the other hand, while using a Setter function. Each class variable should have its own setter method which needs to be invoked for each variable of that class.
Getter function is used to read/access the class variables. There are two methods to access/read a class variable using a return statement or without the return statement.
ClassA
/** * */ package GetterSetter; /** * @author ashok.kumar * */ public class ClassA { int roll; String name; public ClassA(int x, String y) { roll=x; name=y; } }
ClassB
/** * */ package GetterSetter; /** * @author ashok.kumar * */ public class ClassB { int rollB; String nameB; // Setter function for 'rollB' void setrollB(int x) { rollB=x; } // Getter function for 'rollB' void getrollB() { System.out.println(rollB); } // Setter function for 'nameB' void setnameB(String y) { nameB=y; } // Getter function for 'nameB' via return statement. String getnameB() { return nameB; } }
mainClass
/** * */ package GetterSetter; /** * @author ashok.kumar * */ public class mainClass { public static void main(String[] args) { ClassA objA=new ClassA(10,"Rambo"); System.out.println("Value of ClassA object"); System.out.println(objA.roll + " " + objA.name); objA=new ClassA(20,"Ramesh"); System.out.println(objA.roll + " " + objA.name); ClassB objB=new ClassB(); objB.setrollB(20); objB.setnameB("Ajay"); System.out.println("\nValue of ClassB object"); objB.getrollB(); // First method to read/access Class variable. System.out.println(objB.getnameB()); // Alternate method to read/access Class variable. objB.setrollB(30); objB.setnameB("Rajan"); objB.getrollB(); System.out.println(objB.getnameB()); objB.setrollB(40); objB.setnameB("Sonu"); objB.getrollB(); System.out.println(objB.getnameB()); } }
Console Output
Value of ClassA object
10 Rambo
20 Ramesh
Value of ClassB object
20
Ajay
30
Rajan
40
Sonu