Java Example: Data Encapsulation http://www.chankok.com/java-data-encapsulation/
package com.chankok.oop; | |
public class DataEncapsulationExample { | |
public static void main(String[] args) { | |
try { | |
Student student1 = new Student(); | |
student1.setName("Chankok"); | |
student1.setSubject("History"); | |
student1.setMarks(-1); | |
System.out.println("Student 1 Name: " + student1.getName()); | |
System.out.println("Student 1 Subject: " + student1.getSubject()); | |
System.out.println("Student 1 Marks: " + student1.getMarks()); | |
Student student2 = new Student(); | |
student2.setName(null); | |
student2.setSubject("Mathematics"); | |
student2.setMarks(50); | |
System.out.println("Student 2 Name: " + student2.getName()); | |
System.out.println("Student 2 Subject: " + student2.getSubject()); | |
System.out.println("Student 2 Marks: " + student2.getMarks()); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
package com.chankok.oop; | |
public class Student { | |
private String name; | |
private String subject; | |
private int marks; | |
public Student() { | |
this.name = "Default Student Name"; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) throws Exception { | |
if (name == null) { | |
// Not allow to set student name as null value | |
throw new IllegalArgumentException("Student name cannot be null"); | |
} | |
this.name = name; | |
} | |
public String getSubject() { | |
return subject; | |
} | |
public void setSubject(String subject) { | |
this.subject = subject; | |
} | |
public int getMarks() { | |
return marks; | |
} | |
public void setMarks(int marks) { | |
if (marks < 0) { | |
// Not allow to set student marks as negative value, assign default value | |
this.marks = 0; | |
} else { | |
this.marks = marks; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment