Wednesday 24 September 2014

If we are using both constructor and Setter method of a bean to set property of a bean class then with which value it will be set , with value given in constructor or setter method ?


Ans :  With value given by setter method.
Reason : Because constructor will be invoked at the time of object creation but setter method will be invoked after that ,so due to which value of setter method ll override value given by constructor .
Eg. We have bean class Student

Class Student
{
Private int studentID;
Private String studentName;

Public Student(int stuid,String stuName)
{
this.studentID=stuid;
this.studentName=stuName;
}

//getter and setter methods for both
}

Class test
{
Main
{
Student obj=new Student(1,”Manish”);//Constructor will be invoked here
obj.setStudentID(2);//setter method will be invoked here which will override the value given //by Constructor
System.out.println(obj.getStudentID()) ; //will print 2
}

}

No comments:

Post a Comment