-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39_Encapsulation
More file actions
116 lines (101 loc) · 2.31 KB
/
39_Encapsulation
File metadata and controls
116 lines (101 loc) · 2.31 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Encapsulation = attributes of a class will be hidden or private,
// Can be accessed only through methods (Getters & setters)
// You should make attributes private if you don't have a reason to make them public/protected
<Main.java>
public class Main{
public static void main(String[] args){
Car car = new Car("Chevrolet","Camaro",2021);
System.out.println(car.make);
}
}
<Car.java>
public class Car{
private String make;
private String model;
private int year;
Car(String make, String model, int year){
this.make = make;
this.model = model;
this.year = year;
}
}
>>cannot find symbol class B
*To retreive value*
<Main.java>
public class Main{
public static void main(String[] args){
Car car = new Car("Chevrolet","Camaro",2021);
System.out.println(car.getMake());
System.out.println(car.getModel());
System.out.println(car.getYear());
}
}
<Car.java>
public class Car{
private String make;
private String model;
private int year;
Car(String make, String model, int year){
this.make = make;
this.model = model;
this.year = year;
}
public String getMake(){
return make;
}
public String getModel(){
return model;
}
public int getYear(){
return year;
}
}
>>
Chevrolet
Camaro
2021
*To change value of private"
<Main.java>
public class Main{
public static void main(String[] args){
Car car = new Car("Chevrolet","Camaro",2021);
car.setYear(2022);
System.out.println(car.getMake());
System.out.println(car.getModel());
System.out.println(car.getYear());
}
}
<Car.java>
public class Car{
private String make;
private String model;
private int year;
Car(String make, String model, int year){
this.make = make;
this.model = model;
this.year = year;
}
public String getMake(){
return make;
}
public String getModel(){
return model;
}
public int getYear(){
return year;
}
public void setMake(String make){
this.make=make;
}
public void setModel(String model){
this.model = model;
}
public void setYear(Integer year){
this.year=year;
}
}
>>
Chevarolet
Camaro
2022
<