Let us consider we are storing the student details of 3 students. These 3 students are having different values for sno, sname and sage, but all 3 students belongs to same department CSE. So it is better to initialize "dept" variable inside a constructor so that this value can be taken by all the 3 student objects.
To understand clearly, see the below simple example:
class Student
{
int sno,sage;
String sname,dept;
Student()
{
dept="CSE";
}
public static void main(String a[])
{
Student s1=new Student();
s1.sno=101;
s1.sage=33;
s1.sname="John";
Student s2=new Student();
s2.sno=102;
s2.sage=99;
s2.sname="Peter";
Student s3=new Student();
s3.sno=102;
s3.sage=99;
s3.sname="Peter";
System.out.println("The details of student1 are");
System.out.println("The student no is:"+s1.sno);
System.out.println("The student age is:"+s1.sage);
System.out.println("The student name is:"+s1.sname);
System.out.println("The student dept is:"+s1.dept);
System.out.println("The details of student2 are");`enter code here`
System.out.println("The student no is:"+s2.sno);
System.out.println("The student age is:"+s2.sage);
System.out.println("The student name is:"+s2.sname);
System.out.println("The student dept is:"+s2.dept);
System.out.println("The details of student2 are");
System.out.println("The student no is:"+s3.sno);
System.out.println("The student age is:"+s3.sage);
System.out.println("The student name is:"+s3.sname);
System.out.println("The student dept is:"+s3.dept);
}
}
Output:
The details of student1 are
The student no is:101
The student age is:33
The student name is:John
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE