-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncapsulation.java
More file actions
70 lines (56 loc) · 1.85 KB
/
Encapsulation.java
File metadata and controls
70 lines (56 loc) · 1.85 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class Person {
// Encapsulation (Private variables)
private String name;
private int age;
// Validation functions
public static void validateName(String inputName) {
if (inputName == null || inputName.isEmpty()) {
throw new IllegalArgumentException("Name cannot be empty!");
}
}
public static void validateAge(int inputAge) {
if (inputAge < 18) {
throw new IllegalArgumentException("Age must not be a minor!");
}
}
// Constructor with validation
public Person(String name, int age) {
validateName(name);
validateAge(age);
this.name = name;
this.age = age;
}
// Name getter function
public String getName() {
return this.name;
}
// Name setter function
public void setName(String newName) {
validateName(newName);
this.name = newName;
}
// Age getter function
public int getAge() {
return this.age;
}
// Age setter function
public void setAge(int newAge) {
validateAge(newAge);
this.age = newAge;
}
}
public class Encapsulation {
public static void main (String[] args) {
// Person 1:
Person person1 = new Person("Bob", 19);
System.out.println("Hello I am " + person1.getName() + ", and I am " + person1.getAge() + " years old.");
// Person 2:
// This will throw an error because age is minor
Person person2 = new Person("Jake", 15);
System.out.println("Hello I am " + person2.getName() + ", and I am " + person2.getAge() + " years old.");
// Person 3:
// This will also throw an error because name is empty
Person person3 = new Person("", 21);
System.out.println("Hello I am " + person3.getName() + ", and I am " + person3.getAge() + " years old.");
}
}