CODE
class TestStudentMarksImproved
{
public static void main(String arg[])
{
Student madhavan = new Student("Madhavan");
madhavan.setMarks(87, 65, 93);
System.out.println("Subject 1 = " + madhavan.getSubject1Marks());
System.out.println("Subject 2 = " + madhavan.getSubject2Marks());
System.out.println("Subject 3 = " + madhavan.getSubject3Marks());
System.out.println("Total = " + madhavan.getTotalMarks());
// LINE X - THROWS COMPILATION ERROR
// madhavan.subject1 = 87;
// LINE Y - THROWS COMPILATION ERROR
// System.out.println("Subject 1 = " + madhavan.subject1);
}
}
class Student
{
private String name;
private int subject1;
private int subject2;
private int subject3;
private int total_marks;
Student(String name)
{
this.name = name;
}
void setMarks(int subject1, int subject2, int subject3)
{
this.subject1 = subject1;
this.subject2 = subject2;
this.subject3 = subject3;
this.total_marks = subject1 + subject2 + subject3; // LINE A
}
int getSubject1Marks()
{
return subject1; // LINE B
}
int getSubject2Marks()
{
return subject2;
}
int getSubject3Marks()
{
return subject3;
}
int getTotalMarks()
{
return total_marks;
}
}
Subject 1 = 87
Subject 2 = 65
Subject 3 = 93
Total = 245
In this program we have used the private
keyword. private
is an access specifier which prevents a member variable to be accessed from outside the class. e.g., The member variable subject1
is only accessible inside the class Student
. If we try to access it from main
method in the class TestStudentMarksImproved
, it will throw a compilation error.
LINE X
and LINE Y
and observe the compilation error you get.LINE X
and LINE Y
and also remove the private
access specifier for subject1
and see that the program compiles with out any error.