Java foundation -- Inheritance and polymorphism

Keywords: Java C Algorithm

catalogue

1, Package

1. Import classes in package

2. Static import

3. Access control of package

2, Inherit

1. Concept and usage of inheritance

2.protect

3. Summary

 4.final

3, Polymorphism

1. Upward transformation

2. Dynamic binding

2.1 rewriting

2.2 difference between rewriting and overloading

3. Downward transformation

4.super keyword

4, Abstract class

1. Introduction to abstract classes

2. Role of abstract classes

5, Interface

1. Grammar rules

2. Implement multiple interfaces

1, Package

1. Import classes in package

When we use Java programming, we don't realize many things by ourselves like C language. For example, we want to know the length of array. In C language, we will use:

int len = sizeof(arr)/sizeof(arr[0]);

len is the length of the array we want. However, in Java, we don't need to find the array length again. We can use:

int len = arr.length;

But sometimes we need some special functions:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6};
        int[] b = Arrays.copyOf(arr,5);
    }
}

We need to import classes into Java files. Arrays in the above code is a class, and java.util is the package of this class.

Package: 1. Package is a way to organize classes   two   The purpose of using packages is to ensure the uniqueness of classes.

2. Static import

Using import   Static can import some static methods and fields, such as:

import static java.lang.System.*;

public class Test {
    public static void main(String[] args) {
        out.println("hello");
   }
}

Although it simplifies the code, it always looks strange, and the code is not readable. We don't usually do that.

3. Access control of package

As we mentioned before in classes and objects, some class members are modified with private to protect them

However, we often find that if the access modifier qualifier of a member uses public, the scope is too large and the use of private is too small. When we do not add any access modifier qualifiers to the members of a class, its scope is different classes in the same package.

2, Inherit

1. Concept and usage of inheritance

If we want to define a Dog class and a Duck class now, dogs and ducks have their names and ages and need to eat. These are what they have in common as animals. When we define classes, these commonalities obviously need to be defined repeatedly in the two classes. Today, we only define two animal classes. If one day we need to include many kinds of animals because of business needs, do we have to repeat these codes one by one?

In Java, in order to simplify the code, the concept of inheritance is introduced.

Syntax rules: class B extends A{

                                     } 

matters needing attention:

1. A subclass can inherit only one parent class.

2. The subclass will inherit all public members and methods of the parent class.

3.private members and method subclasses cannot inherit.

4. For members and methods of the parent class, subclass objects can be referenced by super.

Take the following code as an example:

public class Animal {  //When a class is modified by final, it cannot be inherited
    public String name;
    public int age;
    protected int score;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("Animal Construction method");
    }

    public void eat() {
        System.out.println(this.name + "I am eating");
    }
}

class Dog extends Animal {//A subclass can inherit only one parent class
    public Dog(String name, int age) {
        super(name, age);//When constructing a subclass, help the parent class to construct it first
        System.out.println("Dog Construction method of");
    }

    public void run() {
        System.out.println(this.name + "Running");
    }

    @Override//Override parent method
    public void eat() {
        System.out.println(this.name + "Devour" + super.name);
        //Notes for rewriting: 1. The method names of parent and child classes are the same, the return values are the same (special case: covariant type), and the parameter list is the same
        //In the case of parent-child classes
        //Methods modified by static, final and private cannot be overridden
        //The access modifier qualifier range of a subclass should be greater than or equal to the parent class
    }

}

When defining the parent class, we may define our own constructor. At this time, we should pay attention to overriding the constructor after the child class inherits the parent class.

Code format:

public   Subclass (String name, int age){
        super(name, age); / / call the parent class constructor
        System. Out. Println ("construction method of dog");

 }
   

Note: Super calling the parent class constructor can only be placed in the first line of the child class constructor, and the super keyword cannot appear in the static method.  

2.protect

As we just said, if the access modifier qualifier of the field in the parent class is set to private, the subclass cannot inherit the method and field of the parent class, but sometimes the subclass needs to access these members because of some requirements. Then we can try to modify the member with protected, which can not only encapsulate but also be accessed by the subclass.

The maximum access range of protected modified members is the parent-child relationship of different packages.

3. Summary

There are four access permissions for fields in Java:

1.private: it can be accessed inside the class, but not outside the class.

2. Default (also known as package access permission): it can be accessed inside a class. Classes in the same package can be accessed, but other classes cannot.
3.protected: the class can be accessed internally. Subclasses and classes in the same package can be accessed. Other classes cannot be accessed.
4.public: both inside the class and the caller of the class can access it.

The above is the accessible range of these four access modifier qualifiers.

 4.final

In our projects, classes are generally allowed to be inherited up to three times in a row. Now, if we don't want a class to be inherited, we can add final before the class name.

Example:

final public class A {
      protected int a;
}

3, Polymorphism

1. Upward transformation

The upward transformation is implemented on the basis of parent-child class inheritance. It can be summarized as follows: parent class references child class objects.

Example:

public class Animal {
    public String name;
}

class Dog extends Animal {//A subclass can inherit only one parent class
    
}

public static void main(String[] args) {
    Animal animal = new Dog("a", 20);//Direct assignment upward transformation
}

There are three types of upward Transformation:

1. Direct assignment (for example).

2. Method transmission parameters:

public static void main(String[] args) {
        fun1(new Dog("Parent class",12));
}

public static void fun1(Animal animal) {//Upward transformation of transmission parameters
        animal.eat();
}

3. Method return:

public static void main(String[] args) {
        fun2(duck).eat();
}

public static Animal fun2(Duck duck) {//The return value is transformed upward
        return duck;
}

2. Dynamic binding

Take the previous parent-child classes as an example: all animals can eat, but different animals eat in different ways and foods. So how do we reflect the differences among the subclasses after inheriting the eat() method of the parent class?

2.1 rewriting

First, let's introduce the concept of override: a subclass implements the method with the same name as the parent class, and the type and number of parameters are exactly the same. This situation is called override / override.

Example:

public class Animal {  //When a class is modified by final, it cannot be inherited
    public String name = "a";

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("Animal Construction method");
    }

    public void eat() {
        System.out.println(this.name + "I am eating");
    }
}

class Dog extends Animal {//A subclass can inherit only one parent class
    public String name = "Dog";

    public Dog(String name, int age) {
        super(name, age);//When constructing a subclass, help the parent class to construct it first
        //super cannot appear inside a static method
        System.out.println("Dog Construction method of");
    }

    @Override//Override parent method
    public void eat() {
        System.out.println(this.name + "Devour" + super.name);
      
    }

}

After operation:

 

  We will find that when a subclass overrides a method of the parent class and the parent class refers to the subclass object to call the function, the system will execute the function rewritten by the subclass by default (the same is true for calling member variables. If there are members with duplicate names in the subclass, the subclass itself will be called first).

Rewriting considerations:

1. Functions modified by final, private and static cannot be rewritten.

2. After rewriting, the variable name, number of parameters and form cannot be changed, and the return value must remain the same (except covariant type (parent-child class)).

3. The override function permission of the subclass must be greater than or equal to that of the parent class.

2.2 difference between rewriting and overloading

1. Override range: parent-child class inheritance relationship             Overloaded scope: in the same class

2. Parameters after Rewriting: remain the same                 Overloaded parameters: at least one of the type and number of formal parameters is different from the original function

3. Rewrite the return value: consistent (except covariance)     Overloaded return value: it is not required. It can be the same, different or not

4. Method name: consistent with the original function

5. Permission restriction: override: must be greater than or equal to the parent function       Overload: no restrictions

3. Downward transformation

Downward Transformation: downward transformation is the transformation of parent objects into child objects. Compared with upward transformation, downward transformation is less common,

But it also has certain uses .
Example:
Duck b = (Duck)a;//Downward transformation, not recommended. Downward transformation can only occur when the subclass you want to transform happens to be the subclass referenced by the parent class

Note: downward transformation can only be performed when the subclass we want to transform happens to be the type referenced by the parent class, otherwise an exception will be thrown. In popular words: Animal refers to the Dog class. We want to transform it downward into Bird, but dogs can't fly, so they will report an error.

Therefore, in order to make the downward transition safer, we can use instanceof to determine:

Animal animal = new Cat("kitten"); 
if (animal instanceof Bird) { 
 Bird bird = (Bird)animal; 
 bird.fly(); 
}

4.super keyword

We mentioned the use of in subclass constructors earlier Super keyword to call the constructor of the parent class. In addition to calling the constructor of the parent class, super can Members and methods of calling the parent class in subclasses (except private)
be careful: super cannot appear in a static method.
The following is the difference between super and this:
1. Function: This accesses the methods and properties of this class     super accesses the methods and properties of the parent class
2. Search range: this first finds itself, and then finds the parent class       super finds the parent class directly
3. this represents the current object

4, Abstract class

1. Introduction to abstract classes

In the previous example, we found that the overridden method in the parent class will not be used. What we have been calling is actually the method overridden by the child class. Then we can further define the parent class as an abstract class.

Example:

abstract public class Animal {
    protected String name;

    abstract protected void eat();

    protected void drink() {
        System.out.println("drink water");
    }
}

Note: 1. Abstract methods cannot be private     2. Abstract classes cannot be instantiated     3. Abstract classes can contain ordinary members and methods, which can be called directly by subclasses or overridden     4. If a subclass inherits an abstract class, it must override the abstract method of the parent class

import com.Animal;

public class Dog extends Animal{
    public void eat() {
        System.out.println("Dog eat");
    }
}

2. Role of abstract classes

Abstract classes exist in order to be inherited.
Abstract classes themselves cannot be instantiated , To use , Only subclasses of this abstract class can be created . Then let the subclass override the abstract methods in the abstract class.

5, Interface

Interfaces are further abstractions of abstract classes. In addition to abstract methods, abstract classes can also define some common fields and methods. However, there can only be abstract methods in the interface, and fields can only be static constants.

1. Grammar rules

public interface IShape {
   void draw(); 
}


public class Cycle implements IShape {
    @Override
    public void draw() {
        System.out.println("○");
    }
}

be careful:

1. Use interface to define an interface

2. The methods in the interface must be abstract methods, and abstract can be omitted

3. The methods in the interface must be public methods, so public can be omitted

4.Cycle inherits the interface with implements, which means implementation.

5. The interface cannot be instantiated

2. Implement multiple interfaces

Sometimes, a subclass needs to inherit more than one parent class. However, a subclass can only inherit one parent class, so we introduce the concept of interface. A subclass can inherit multiple interfaces.

Example:

public class Cycle implements IShape, IColor {
    @Override
    public void draw() {
        System.out.println("○");
    }

    @Override
    public void color() {
        System.out.println("red");
    }
}

Advantages of using interfaces: forget types. With interfaces, class users don't have to focus on specific types, but only on whether a class has certain capabilities

Posted by IThinkMyBrainHurts on Wed, 17 Nov 2021 02:53:54 -0800