In this tutorial, we will write an encapsulation program in java. Before that, you should have knowledge on the following topic in Java.
Encapsulation in Java using setter and getter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | class StudentInfo { private int id; private String stdName; private int stdAge; //Getter methods public int geStdiID() { return id; } public String getStdName() { return stdName; } public int getStdAge() { return stdAge; } // Setter methods public void geStdiID(int newId) { id = newId; } public void getStdName(String newName) { stdName = newName; } public void getStdAge(int newAge) { stdAge = newAge; } } public class EncapsTest { public static void main(String args[]) { StudentInfo obj = new StudentInfo(); obj.geStdiID(1101); obj.getStdName("Marshall"); obj.getStdAge(20); System.out.println("Student Id: " + obj.geStdiID()); System.out.println("Student Name: " + obj.getStdName()); System.out.println("Student Age: " + obj.getStdAge()); } } |
Output:
Student Id: 1101
Student Name: Marshall
Student Age: 20