Last active
February 2, 2017 06:29
-
-
Save chankok/d866315b982a31e26dcb7e2a86f8f780 to your computer and use it in GitHub Desktop.
Java Example: Data Encapsulation http://www.chankok.com/java-data-encapsulation/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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