Data Encapsulation
Data Abstraction and Access Labels
- 1) Providing only essential information to the outside world and hiding their background details
- 2) Seperate interface and implementation
- 3) Access Labels: public, private, protected, default
Access | public | protected | private |
---|---|---|---|
Same class | yes | yes | yes |
Derived class | yes | yes | no |
Outside class | yes | no | no |
Access Levels
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
no modfier(default) | Y | Y | N | N |
private | Y | N | N | N |
- public - everyone can access
- private - only myself can access(but only at class level, other objects of the same class can access as well)
- protected - only my children and same package can access
- default - only the same package can access
Advantages
Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object.
The class implementation may evolve over time in response to changeing requirements or bug reports without requiring change in user-level code(easier to maintain the compatibility).
public class Employee {
private final String name;
private final String id;
private int age;
private int salary;
private int level;
Employee(String name, int age, String id, int level) {
this.name = name;
this.age = age;
this.id = id;
this.level = level;
}
public String getName(){
return this.name;
}
...
}
Q: how to select appropriate labels?
给尽量低的权限!!!
- 1 API:public
- 2 Internal implementation: private
3 Class inheritance: do we need to use protected for methods/attributes a. Protected methods: sometimes useful when we want to override an implementation in subclass b. Protected attributes: be careful, try to use private first
4 "default" in java (package-private):declare a class as public only when we define public API in it, otherwise package-private is good enough.