19. java object-oriented - Encapsulated

1. encapsulation embodies

Property privatization (private) we would like, while providing a common (public) method to get (getXxx) and set the value of this property (setXxx). Expansion: ① not exposed to outside private method ② Singleton

Second, the authority modifier

Modifiers Inner classes The same package Different classes buns The same project
private Yes
default Yes Yes
protected Yes Yes Yes
public Yes Yes Yes Yes

For the privilege class can only use public and default. Four permission can be used to modify the internal structure of the class and class: properties, methods, constructors, class interior;

  • public class can be accessed anywhere
  • default classes can only be the same type of access the interior of a package
public class Animal {
    String name;
    private int age;
    //设置值
    public void setAge(int formAge) {
        if (formAge < 0 || formAge >130) {
            throw new RuntimeException("传入值非法!");
        } else {
            age = formAge;
        }
    }
    //取值
    public int getAge(){
        return age;
    }
}


class animalTest{
    public static void main(String[] args) {
        Animal anl = new Animal();
        // anl.setAge(131);
        anl.setAge(10);
        System.out.println(anl.getAge());
    }
}

Guess you like

Origin www.cnblogs.com/hq82/p/12128959.html