Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to implement Object Oriented Programming Encapsulation feature in Java programming language?

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;
 }
}



 
© 2021 Learn Java by Examples Template by Hubberspot