Encapsulation, inheritance and polymorphism of object-oriented programming

Introduction

         Hello, everyone, today we share a very important module in our java language - object-oriented.

catalogue

Introduction

Article catalog

1, Object oriented

    1.1 object oriented overview 

    1.2 three characteristics of object-oriented -- encapsulation, inheritance and polymorphism

         1.2.1 packaging

        1.2.2 inheritance

        1.2.3 polymorphism

Summary:


1, Object oriented

        1.1 object oriented overview

        When we come into contact with programming languages, some people always mention object-oriented programming (OOP), so what is object-oriented? I believe the first program you just started to write is helloworld. So the helloworld program is very simple. It is an output statement. After we understand object-oriented programming, we should learn to encapsulate what we want to do into an object to realize the function we want.

        

 

         Long ago, programming was process oriented, such as implementing an arithmetic operation 1 + 1 = 2. The problem can be solved through this simple algorithm. However, with the progress of the times, people are not satisfied with the existing algorithms, because the problem is more and more complex, not as simple as 1 + 1. For example, the data analysis of students in a class has the concept of object, and everything is an object. Abstract the real things. Note that the word abstraction is the key. Abstract the real life things and relations into classes, and accommodate everything through inheritance, realization and combination. It realizes the abstraction and mathematical modeling of the real world. This is a leap forward.

        So what's the difference between object-oriented and process oriented? These two concepts are very abstract. Let's give two examples to understand, such as eating

1. You go home and cook by yourself one day. You buy vegetables, wash vegetables, light a fire, add ingredients, fry, plate and eat.

2. Go to the restaurant, boss. Have shredded beef with green pepper! You: OK!

         Did you see? You can get the food you want directly when you go to the hotel. It's convenient! You don't need to know how this dish is made. You can eat it, which reduces the coupling of our "eating". Moreover, if you cook by yourself, you suddenly don't want to eat this dish. If you want to change your taste, I'm afraid the first way will be much more troublesome, while the second way you just need to shout: "boss, don't want shredded beef with green pepper, and divide shredded pork with fish flavor." I believe 100% can. Reduces the maintainability of our program.

        After understanding object-oriented and process-oriented, we must master the three characteristics and six principles of object-oriented.

1.2 three characteristics of object-oriented -- encapsulation, inheritance and polymorphism

         1.2.1 packaging

        We have also shared about classes and objects before. If you don't know, you can turn it forward. Here we briefly review classes:

        A class is a template or blueprint for constructing objects. We can think of class as the secret recipe for making dishes and object as dishes. The process of constructing objects from classes is called creating instances of classes.

        Definition and principle of encapsulation: some information of a class is hidden inside the class (so encapsulation is also called data hiding). External programs are not allowed to access directly, but the operation and access of hidden information are realized through the methods provided by the class.

         Advantages of encapsulation: the operation of member variables is controlled by methods, which improves the security of the code
The code is encapsulated by method, which improves the reusability of the code.

         Encapsulation is like we handed over the steps of cooking to the chef. We can order what we need directly. We don't need to do anything.

        We have also shared some details about packaging. You can also turn it forward!

        1.2.2 inheritance

        Before sharing inheritance, we also share the relationship between two common classes: dependency and aggregation

         The relationship of uses-a is the most obvious and common relationship. If the methods of one class use or manipulate the objects of another class, we say that one class depends on another class. For example, our menu class and our chef's cooking class. If a chef wants to cook, the chef class needs a menu class because he needs to view the menu object to see how he wants to cook. In our development, we should reduce dependencies and coupling between classes as much as possible. The key here is that if class A does not know the existence of class B, he will not care about any change of class B (that is, the change of B will not lead to any bug of class a);

        Aggregation is the relationship of (has a). For example, my class A contains some class B objects, and these two classes have this aggregation relationship.

        When it comes to our inheritance, it is an (is-a) relationship, which represents the relationship between a more special class and a more general class, such as my menu class and stir fry class. Our more special stir fry class contains some special methods for priority processing, such as ignition, etc., and the order method of the quantity of dishes is inherited from the menu class.

        Then inheritance can make subclasses have the properties and methods of the parent class, redefine them in subclasses, and append properties and methods.

         So how to implement inheritance in java?

         In java, we use the keyword extends to implement the inheritance between two classes. Extends indicates that the new class being constructed derives from an existing class. His format is:

         Class subclass extends parent class {}; For example: class dog extensions animal {};.

         The benefits of inheritance are: inheritance can create a relationship between classes and a child parent relationship. After a child parent class is generated, the child class can use the non private members of the parent class;

         For example, our code here:         

public class Fu {
    public void show() {
        System.out.println("show Method called");
    }
}
public class Zi extends Fu {
    public void method() {
        System.out.println("method Method called");
    }
}
public class Demo {
    public static void main(String[] args) {
        //Create an object and call a method
        Fu f = new Fu();
        f.show();

        Zi z = new Zi();
        z.method();
        z.show();
    }
}

         Output results

show Method called
method Method called
show Method called

Then we obviously found that the show method in our subclass was magically called, which is inheritance.

Inheritance considerations:
    1. Subclasses are not subsets of the parent class. Subclasses generally contain more data fields and methods than the parent class.
    2. The private data fields in the parent class are invisible in the child class, so they cannot be used directly in the child class.
    3. Inheritance models the relationship of "is-a". There must be an "is-a" relationship between the parent class and its subclasses, otherwise inheritance cannot be used.
    4. But not all "is-a" relationships should use inheritance. For example, a Square is a Rectangle, but you can't let the Square class inherit the Rectangle class, because a Square can't extend anything from a Rectangle. The correct inheritance relationship is that the Square class inherits the Shape class
    5. Java only allows single inheritance (that is, a subclass can only have one direct parent class and multiple inheritance), and C + + can inherit multiple (that is, a subclass can have multiple direct parents).

A small problem in inheritance: Method rewriting

Method rewrite
     1. Method rewrite concept
         As like as two peas, the subclass has the same method declaration as the parent class (the same as the method name, and the parameter list must be the same).
     2. Application scenario of method rewriting
         When a subclass needs the function of the parent class and the subclass of the function subject has its own unique content, you can override the methods in the parent class. In this way, you can not only follow the function of the parent class, but also define the unique content of the subclass.
     3.@override annotation
         It is used to detect whether the current method is a rewritten method and plays the role of (verification)
Method override considerations
         1. Private method cannot be overridden (private member subclasses of parent class cannot inherit)
         2. Subclass method access permission cannot be lower (public > Default > private)
     Sample code
      

 public class Fu {
    private void show() {
        System.out.println("Fu in show()Method called");
    }

    void method() {
        System.out.println("Fu in method()Method called");
    }
}

public class Zi extends Fu {

    /* Compile [error], the subclass cannot override the private method of the parent class*/
    @Override
    private void show() {
        System.out.println("Zi in show()Method called");
    }
   
    /* Compile [error]. When the subclass overrides the parent method, the access permission must be greater than or equal to the parent */
    @Override
    private void method() {
        System.out.println("Zi in method()Method called");
    }

    /* Compile [pass]. When the subclass overrides the parent method, the access permission must be greater than or equal to that of the parent */
    @Override
    public void method() {
        System.out.println("Zi in method()Method called");
    }
}

1.2.3 polymorphism

        Polymorphism is one of the three characteristics of object-oriented.
        Polymorphism refers to the different forms of the same object at different times. Polymorphism refers to the same interface, using different instances to perform different operations.

In real life, for example, students are a kind of people, but one of his specific implementations is Li Si. He is both a student and a person, and so is the teacher. The specific implementation object of the teacher is Li Minghua. He is both a teacher and a person.
     The premise of polymorphism is to have inheritance or implementation relationship   There should be method overrides and parent class references pointing to subclass objects: Parent p = new Child();
      

Characteristics of members in polymorphism
Polymorphic member variables: see the left side of the compilation run
         Fu f=new Zi();

          System.out.println(f.num);//f is the value in Fu. Only the value in the parent can be obtained

  Polymorphic member method: compile to the left and run to the right

        Fu f1=new Zi();

        System.out.println(f1.show());// The surface type of F1 is Fu, but the actual type is Zi, so the overridden method is called. Why are member methods different from member variables? Because member methods have overrides.
 

    Advantages and disadvantages of polymorphism
     benefit
         Improve the scalability of the program. When defining a method, use the parent type as a parameter, and then use the specific subtype to participate in the operation
     malpractice
         Unique members of subclasses cannot be used

Transformation in polymorphism
     1. Upward transformation
         From child to parent: the parent class reference points to the child class object, which is the upward transformation
            Animal  a = new Cat();
     2. Downward transformation
         From parent to child: parent class references are converted to child class objects
             Format: subtype object name = (subtype) parent class reference;
                Cat c = (Cat )a;
     Sample code
      

  public class Test {
    public static void main(String[] args) {
      show(new Cat());  // Call the show method as a Cat object
      show(new Dog());  // Call the show method with a Dog object
                
      Animal a = new Cat();  // Upward transformation  
      a.eat();               // Cat eat is called
      Cat c = (Cat)a;        // Downward transformation  
      c.work();        // Cat work is called
  }  
            
    public static void show(Animal a)  {
      a.eat();  
        // Type judgment
        if (a instanceof Cat)  {  // What cats do  
            Cat c = (Cat)a;  
            c.work();  
        } else if (a instanceof Dog) { // What dogs do  
            Dog c = (Dog)a;  
            c.work();  
        }  
    }  
}
 
abstract class Animal {  
    abstract void eat();  
}  
  
class Cat extends Animal {  
    public void eat() {  
        System.out.println("Eat fish");  
    }  
    public void work() {  
        System.out.println("Catch a mouse");  
    }  
}  
  
class Dog extends Animal {  
    public void eat() {  
        System.out.println("Eat bones");  
    }  
    public void work() {  
        System.out.println("Housekeeping");  
    }  
}
        Output results
            Eat fish
 Catch a mouse
 Eat bones
 Housekeeping
 Eat fish
 Catch a mouse

Here is a cat and dog case to help you understand polymorphism more deeply

​​​​​​​

 

Animals:

public class Animal {
    private String name;
    private int age;

    public Animal() {
    }

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public void eat() {
        System.out.println("Animals eat");
    }
}

Cats:

public class Cat extends Animal {

    public Cat() {
    }

    public Cat(String name, int age) {
        super(name, age);
    }

    @Override
    public void eat() {
        System.out.println("Cats eat fish");
    }
}

    Test class:

public class AnimalDemo {
    public static void main(String[] args) {
        //Create cat objects for testing
        Animal a = new Cat();
        a.setName("Garfield");
        a.setAge(5);
        System.out.println(a.getName() + "," + a.getAge());
        a.eat();

        a = new Cat("Garfield", 5);
        System.out.println(a.getName() + "," + a.getAge());
        a.eat();
    }
}

Summary:

         We will share the three major features of object-oriented encapsulation, inheritance and polymorphism here first. Later, we will share more comprehensive cases and details. We welcome your continuous attention.
        ​​​​​​​
        

 

 

 

 

 

Tags: Java

Posted on Wed, 15 Sep 2021 16:09:11 -0400 by imagineek