Boring JavaEE from entry to abandonment (9) Detailed encapsulation & detailed polymorphism

table of Contents

1. Encapsulation

1. The role and meaning of encapsulation

2. Specific advantages of encapsulation in programming:

3. The realization of encapsulation-the use of access control symbols

4. Two details about protected:

5. Simple rules for encapsulation in development

6.javaBean

2. Polymorphism

1. Polymorphism concept and implementation

2. The main points of polymorphism

3. Sample code


1. Encapsulation

1. The role and meaning of encapsulation

I want to watch TV, just press the switch and change the channel. Is it necessary to understand the internal structure of the TV? Is it necessary to touch the picture tube? In order to facilitate our use of the TV, the manufacturer encapsulates all the complicated internal details and only exposes simple interfaces, such as the power switch. We don't need to worry about how the specific internal implementation is achieved. What needs to be known to the user is exposed, and all that needs to be known to the user is not hidden. This is encapsulation. To be more professional, encapsulation is to combine the properties and operations of the object into an independent whole, and hide the internal implementation details of the object as much as possible. Our program design should pursue "high cohesion, low coupling". High cohesion means that the details of the internal data operation of the class are completed by themselves, and external interference is not allowed; low coupling means that only a small number of methods are exposed for external use, and it is convenient for external calls as much as possible.

2. Specific advantages of encapsulation in programming:

Improve the security of the code.
Improve code reusability.
"High Cohesion": Encapsulate details to facilitate modification of internal code and improve maintainability.
"Low coupling": Simplify external calls, facilitate the use of callers, and facilitate expansion and collaboration.

3. The realization of encapsulation-the use of access control symbols

Java uses "access control symbols" to control which details need to be encapsulated and which details need to be exposed. The four types of "access control symbols" in Java are private, default, protected, and public. They illustrate the object-oriented encapsulation, so we should use them to minimize access rights as much as possible to improve security. The following describes their access rights in detail. The scope of its access authority is shown in the figure below.

(1) private express private, only their own class can access
(2) default indicates no modifier modification, only class in the same package can access
(3) protected representation may be a subclass of class with a package and other packages visit

Note: The difference between public static and static:

In fact, it is the difference of access permissions, one is public and the other is default.

4. Two details about protected:

1. If the parent class and the child class are in the same package, the child class can access the protected members of the parent class and the protected members of the parent class object.
2. If the subclass and the parent class are not in the same package , the subclass can access the protected members of the parent class but not the protected members of the parent class object .

eg:

First, the two classes are in different packages.

Code:

Test1.java

public class Test1 {
    private int testPrivate=100;
    int testDefault=200;
    protected int testProtected=300;

    public void test(){
        System.out.println(this.testPrivate);//只有本类可以用私有成员
        System.out.println(this.testDefault);//同一个包的类就能用默认成员
    }
}

Test2.java

import com.company.Test.a.Test1;

public class Test2 extends Test1{
    public void fun(){
        System.out.println(super.testProtected);//子类可访问父类的protected成员
    }

    public static void main(String[] args) {
        Test1 test1=new Test1();
        test1.test();
        Test2 test2=new Test2();
        test2.fun();
        //System.out.println(test.testProtected); 报错,即不能访问父类对象的protected成员

    }

}

Output:

100
200
300

5. Simple rules for encapsulation in development

Private access permissions are generally used.
Provide corresponding get/set methods to access related attributes. These methods are usually publicly modified to provide attribute assignment and read operations (note: the get method of boolean variables starts with is! ).
Some auxiliary methods that are only used in this class can be decorated with private, and it is hoped that methods called by other classes will be decorated with public.

6.javaBean

A simple javaBean example:

The function can be generated directly by right-clicking--"Generate, and you can also use the shortcut key Alt+Insert to quickly open Generate. The idea is very smart. If you don't use the right-click to generate, directly hit a set or get and the corresponding shortcut generation function prompt will appear. I have to say that idea is really smart.

public class Person {
    private String age;
    private String name;
    private boolean flag;

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}

2. Polymorphism

1. Polymorphism concept and implementation

Polymorphism refers to the same method call, which may have different behaviors due to different objects. In real life, the same method, the specific implementation will be completely different. For example: the same method of calling people "rest", Zhang San is sleeping, Li Si is traveling, teacher Gao Qi is typing codes, and the math professor is doing math problems; the same is calling people "eat", Chinese people use chopsticks For meals, the British eat with a knife and fork, and the Indians eat with their hands.

2. The main points of polymorphism

(1) Polymorphism is method polymorphism, not attribute polymorphism (polymorphism has nothing to do with attributes)
(2) The existence of polymorphism must have 3 necessary conditions: inheritance, method rewriting, and parent class references pointing to subclass objects .
(3) After the parent class reference points to the child class object, use the parent class reference to call the method overridden by the child class. At this time, polymorphism occurs.

3. Sample code

Experience the benefits of polymorphism through code: If there is no polymorphism, some places need a lot of rewriting!

There is also some knowledge of type transformation, and I read it by the way.

public class Animals {
    public void shout(){
        System.out.println("叫了一声!");
    }

    //用static声明,animalShout()就是类方法,所以可以直接用函数名调用!!!!
    public static void animalShout(Animals a){ //到了这里相当于将传入的具体的动物类转化为Animals类
        a.shout();//这里会调用传入的具体的动物类的shout()函数
    }

    public static void main(String[] args) {
        Cat cat=new Cat();
        cat.catchMouse();
        animalShout(cat);
        //Dog dog=(Dog)cat;转换不了
        Animals a=new Dog();//向上类型转换,自动的
        Dog dog=(Dog)a;//强制类型转换,向下类型转换
        dog.guard();
        //报错,因为此时a已经转为Dog类型了,所以不能转换为Cat
        //Cat cat1=(Cat)a;
        //cat1.catchMouse();
    }
}

//多态的存在要有3个必要条件:继承,方法重写,父类引用指向子类对象。
class Dog extends Animals{
    @Override
    public void shout() {
        System.out.println("汪汪汪!");
    }

    public void guard(){
        System.out.println("狗看门!");
    }
}

class Cat extends Animals{
    @Override
    public void shout() {
        System.out.println("喵喵喵");
    }

    public void catchMouse(){
        System.out.println("猫抓老鼠!");
    }
}

class Mouse extends Animals{
    @Override
    public void shout() {
        System.out.println("吱吱吱");
    }
}

Output:

猫抓老鼠!
喵喵喵
狗看门!

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_44593822/article/details/115358852