-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencapsulation.java
47 lines (46 loc) · 1.03 KB
/
encapsulation.java
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
class Person
{
private String name;
private int age;
// Getter for name
public String getName()
{
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for age
public int getAge()
{
return age;
}
// Setter for age
public void setAge(int age)
{
if (age >= 0 && age <= 120)
{
this.age = age;
}
else
{
System.out.println("Invalid age. Age must be between 0 and 120.");
}
}
}
public class encapsulation
{
public static void main(String[] args)
{
Person person = new Person();
// Using setter methods to set values
person.setName("John Doe");
person.setAge(30);
// Using getter methods to retrieve values
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
// Trying to set an invalid age
person.setAge(150);
}
}