Java encapsulation, inheritance, polymorphism

I. Introduction

​ Today, I will summarize the three major features of Java, encapsulation, inheritance, and polymorphism. In fact, the three major features are basic for programmers. After all, as long as you get in touch with Java, you need to know these first, and then I will summarize them systematically.

Second, packaging

Let’s talk about one of the features first: encapsulation

2.1, what is encapsulation

Encapsulation (Encapsulation) is an important principle of the object-oriented method, which is to combine the properties and operations (or services) of the object into an independent whole, and hide the internal implementation details of the object as much as possible.

  • Some information of the class is hidden inside the class, and external programs are not allowed to make direct access calls.
  • The operation and access to hidden information is realized through the methods provided by this class.
  • Hide object information.
  • Set aside the external interface for access.

​ Take a more popular example, such as our USB interface. If we need peripherals and only need to connect the device to the USB interface, how it works internally is not important to the user. The USB interface is the access interface provided externally.

Having said so much, why use encapsulation?

2.2, the characteristics of the package

  • Implement more precise control over member variables.
  • Encapsulation can hide the details of internal program implementation.
  • Good encapsulation can reduce the coupling between codes.
  • External members cannot modify the packaged program code.
  • It facilitates data inspection, helps to protect the integrity of object information, and also improves program security.
  • It is easy to modify and improves the maintainability of the code.

2.3, the use of packaging

  • Use the private modifier to indicate minimal access rights.

  • For access to member variables, setXXX and getXXX methods are provided uniformly.

    Let's look at a Student entity object class:

    public class Student implements Serializable {
        
        private Long id;
        private String name;
        private Integer sex;
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getSex() {
            return sex;
        }
    
        public void setSex(Integer sex) {
            this.sex = sex;
        }
    }
    
    

    Analysis: For the above entity object, I think everyone is already familiar with it. The member variables in the object are privatized and cannot be accessed by external programs. But we provide external access methods, which are the set and get methods.

    ​ For such an entity object, the external program only has the authority to assign and obtain values, and cannot modify the internal ones. Therefore, we can also make some logical judgments internally to meet our business needs.

    ​ At this point, we should understand how important encapsulation is to our program. Now let's talk about inheritance.

    Three, inheritance

    3.1, what is inheritance

    Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance fields and methods of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class. Of course, if you have a private attribute (private modification) in the parent class, the subclass cannot be inherited.

    3.2, the characteristics of inheritance

    1. Notes on inheritance:

    ​ Only single inheritance is supported, that is, a subclass is only allowed to have one parent class, but multi-level inheritance can be achieved, and the subclass has a unique parent class, and the parent class can also inherit.

    Subclasses can have the properties and methods of the parent class.

    Subclasses can have their own properties and methods.

    Subclasses can override the methods of the parent class.

    2. Inherited features:

       提高代码复用性。
    
       父类的属性方法可以用于子类。
    
       可以轻松的定义子类。
    
       使设计应用程序变得简单。
    

    3.3, the use of inheritance

    ​1. In the parent-child class relationship inheritance, if the member variable has the same name, there are two ways to access it when creating a subclass object.

    a, access member variables directly through subclass objects

    ​ Whoever is on the left of the equal sign will be used first, and if there is no one, look up.

    b, access member variables indirectly through member methods

    Whoever the method belongs to will use it first, and if not, look up.

    public class FU {
        int numFU = 10;
        int num = 100;
        public void method(){
            System.out.println("父类成员变量:"+numFU);
        }
        public void methodFU(){
            System.out.println("父类成员方法!");
        }
    }
    
    public class Zi extends FU{
        int numZi = 20;
        int num = 200;
        public void method(){
            System.out.println("子类成员变量:"+numFU);
        }
        public void methodZi(){
            System.out.println("子类方法!");
        }
    }
    
    public class ExtendDemo {
        public static void main(String[] args) {
            FU fu = new FU();
            // 父类的实体对象只能调用父类的成员变量
            System.out.println("父类:" + fu.numFU);   // 结果:10
            
            Zi zi = new Zi();
            System.out.println("调用父类:" + zi.numFU); // 结果:10
            System.out.println("子类:" + zi.numZi);   // 结果:20
    
            /** 输出结果为200,证明在重名情况下,如果子类中存在则优先使用,
             *  如果不存在则去父类查找,但如果父类也没有那么编译期就会报错。
             */
            System.out.println(zi.num); // 结果:200
            /**
             * 通过成员方法调用成员变量
             */
            zi.method();    // 结果:10
        }
    }
    

    2. Similarly:

    ​ The member method is the same. Whoever created the object will be used first, and if there is no object, look up directly.
    ​Notes :

    ​ Whether it is a member variable or a member method, if there is no member, it will be searched up to the parent class, and it will never be searched down to the subclass.

    3. In the inheritance relationship, about the use of member variables:

    ​ Local member variables: direct use
    Member variables of this class: this. member variables
    Parent class member variables: super. parent class member variables

    int numZi = 10;
     public void method() {
       int numMethod = 20;
       System.out.println(numMethod);  // 访问局部变量
       System.out.println(this.numZi); // 访问本类成员变量
       System.out.println(super.numFu); // 访问本类成员变量
    }
    

    3.4, rewriting, overloading

    ​Override

    ​ It is the subclass rewriting the implementation process of the access-allowed method of the parent class, and the return value and formal parameters cannot be changed. That is, the shell remains unchanged, but the core is rewritten!

    class Animal{
       public void move(){
          System.out.println("动物行走!");
       }
    }
     
    class Dog extends Animal{
       public void move(){
          System.out.println("狗可以跑和走");
       }
    }
     
    public class TestDog{
       public static void main(String args[]){
          Animal a = new Animal(); // Animal 对象
          Animal b = new Dog(); // Dog 对象
          a.move();// 执行 Animal 类的方法
          b.move();//执行 Dog 类的方法
       }
    }
    

    ​ Rewritten rules:

    1. The parameter list must be the same as the overridden method.

    2. Access rights cannot be lower than those of overridden methods in the parent class (public>protected>(default)>private).

    3. The methods of the parent class members can only be overridden by its subclasses.

    4. Methods modified by final cannot be overridden.

    5. The construction method cannot

    overload

    ​ is in a class, the method names are the same, but the parameters are different. The return types can be the same or different. Each overloaded method (or constructor) must have a unique list of parameter types.

    The most commonly used place is the overloading of the constructor.

   public class Overloading {
       public int test(){
           System.out.println("test1");
           return 1;
       }
       public void test(int a){
           System.out.println("test2");
       }   
       //以下两个参数类型顺序不同
       public String test(int a,String s){
           System.out.println("test3");
           return "returntest3";
       }   
       public String test(String s,int a){
           System.out.println("test4");
           return "returntest4";
       }    
       public static void main(String[] args){
           Overloading o = new Overloading();
           System.out.println(o.test());
           o.test(1);
           System.out.println(o.test(1,"test3"));
           System.out.println(o.test("test4",1));
       }
   }

​ Overload rules:

1. The overloaded method must change the parameter list (the number or type of parameters is different).

2. The overloaded method can change the return type.

3. The overloaded method can change the access modifier.

3.5, this, super keywords

Usage of the super() keyword
​ 1. In the member method of the subclass, access the member variable of the parent class.

2. In the member methods of the subclass, access the member methods of the parent class.
3. In the construction method of the subclass, access the construction method of the parent class.

usage of this keyword:
​ 1. In the member methods of this class, access the member variables of this class.
2. In the member method of this class, access another member method of this class.
3. In the construction method of this class, access another construction method of this class.
Note:

  • The this keyword is the same as super, it must be the first statement of the construction method, and it is unique.
  • this and super cannot exist at the same time.

3.6, Constructor

​In the inheritance
​ 1. There is a default implicit super(); call in the sub-class construction method, so the parent class construction method must be called first, and then the sub-class construction method .
2. Subclass construction can use super(); to call the overloaded construction of the parent class. (Overloading)
​ 3. The super(); parent class call constructor must be in the first line of the subclass construction, which is the element ending with the first ; number, and it can only be called once.

3.7, Notes on inheritance:

1. The Java language is single-inherited, and a subclass can only have one parent class.
2. The Java language can be multi-level inheritance. A subclass has a parent class, and a parent class can also have a parent class.
3. A subclass has only one parent class, but a parent class can have multiple subclasses.

Fourth, polymorphism

4.1, what is polymorphism

Polymorphism is the ability to have multiple different manifestations or forms of the same behavior.

4.2, the characteristics of polymorphism

1. Eliminate the coupling relationship between types and achieve low coupling.

2. Flexibility.

3. Scalability.

4. Replaceability.

4.3, the embodiment of polymorphism

  • inherit

  • Parent class reference points to child class

  • rewrite

    ​Note : In polymorphism, compile to the left and run to the right

   public class MultiDemo {
       public static void main(String[] args) {
           // 多态的引用,就是向上转型
           Animals dog = new Dog();
           dog.eat();
           
           Animals cat = new Cat();
           cat.eat();
           
           // 如果要调用父类中没有的方法,则要向下转型
           Dog dogDown = (Dog)dog;
           dogDown.watchDoor();
   
       }
   }
   class Animals {
       public void eat(){
           System.out.println("动物吃饭!");
       }
   }
   class Dog extends Animals{
       public void eat(){
           System.out.println("狗在吃骨头!");
       }
       public void watchDoor(){
           System.out.println("狗看门!");
       }
   }
   class Cat extends Animals{
       public void eat(){
           System.out.println("猫在吃鱼!");
       }
   }

4.4, upward transformation

1,格式:父类名称 对象名 = new 子类名称(); 
      含义:右侧创建一个子类对象,把它当作父类来使用。
      注意:向上转型一定是安全的。
      缺点:一旦向上转型,子类中原本特有的方法就不能再被调用了。	

Five, interface

​ Finally, regarding the details of the interface, the differences between different versions.

Problem Description:

​ Now a public method needs to be extracted from the interface to solve the problem of code duplication in the default method.
​ But this common method cannot be implemented by the implementation class, so it should be set as private.

After JDK8:

​ 1, default modification, the default method is allowed to be defined in the interface, but the default method can also be overwritten and rewritten.
2. Static methods are allowed to be defined in interfaces.

After JDK9:

1. Ordinary private method, which solves the problem of code duplication between multiple default methods.
2. Static privatization to solve the problem of code duplication between multiple static methods.
​Interface  Notes:
​ 1. The static method in the interface cannot be called through the implementation class object of the interface.
​Correct syntax: interface name calls static method.

The use of constants in the interface:

1. Constants defined in the interface: public static final can be omitted.
2. Constants defined in the interface: must be assigned.
3. Constants defined in the interface: the names of the constants should be all capitalized, and multiple names should be separated by underscores.

Notes on using the interface:

1. An interface has no static code blocks or construction methods
. 2. The direct parent class of a class is unique, but a class can implement multiple interfaces at the same time.
3. If the implementation class does not override all the abstract methods in the interface, then the implementation class must be an abstract class.
4. If the implementation class implements multiple interfaces and there are repeated abstract methods, then only the override is required Once is enough.
5. In Java, if the directly inherited parent class of the implementing class conflicts with the implementing interface, the parent class has higher priority than the interface.

The relationship between interfaces:

1. There is an inheritance relationship between multiple interfaces.
2. If the default method is repeated among multiple parent interfaces, the sub-interface must override the default method.

Six, summary

​ The characteristics of Java are basically summarized, and of course there are still some details that have not been perfected. In fact, these Java basics must be mastered and memorized, because this is closely related to our actual development. Only good coding habits can create good products and be recognized by the society.

​ The above summary is all from my own learning. If there is any discomfort, please leave a message (email) for advice.

Thanks for reading!

Guess you like

Origin blog.csdn.net/qq_42514371/article/details/122733995
Recommended