Program to demonstrate how to implement Object Oriented Programming Encapsulation feature in Java programming language.
package com.hubberspot.oops;
public class Student {
private String name;
private int marks;
private int age;
public int getMarks() {
return marks;
}
// By encapsulation instance variables we can
// safely implement security variables data.
// Data's integrity is maintained as we can set
// and get value of instance variable through
// getters and setters
// It also prevent unwanted access of variables to other
// classes which can corrupt the data.
public void setMarks(int marks) throws MarkException{
if(marks >= 0){
this.marks = marks;
}
else {
throw new MarkException("Marks cannot be negative");
}
}
public int getAge() {
return age;
}
public void setAge(int age) throws IllegalAgeException {
if(age >= 0){
this.marks = marks;
}
else {
throw new IllegalAgeException("Age cannot be negative");
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}