Java class and inheritance

1. Java subclass and parent class

Inheritance is a mechanism for creating new classes from existing classes. Using inheritance, we can first define a general class with common attributes, and then define a subclass with special attributes based on the general class. The subclass inherits the attributes of the general class and Behavior , and add new properties and behaviors of its own as needed. The class obtained by inheritance is called a subclass, and the inherited class is called a parent class (superclass).

Notice:

Java does not support multiple inheritance, that is, a subclass can only have one parent class. People habitually call the relationship between a subclass and a parent class an "is-a" relationship.

In the class declaration, the subclass of a class is defined by using the keyword extends, the general format is:

class 子类名 extends 父类名 {
    
    
}

For example:

class Student extends People {
    
    
}

Define the Student class as a subclass of the People class, and the People class is the parent class (super class) of the Student class.

Class tree structure:

If C is a subclass of B, and B is a subclass of A, it is customary to say that C is a descendant of A. Java classes form a tree structure according to the inheritance relationship (the class is regarded as a node on the tree). In this tree structure, the root node is the Object class (Object is a class in the java.lang package), that is, Object is The ancestor class of all classes. Any class is a descendant of the Object class, and each class (except the Object class) has one and only one parent class, and a class can have multiple or zero subclasses.

Notice:

If a class (except the Object class) does not use the extends keyword in its declaration, the class is assumed to be a subclass of Object by default. Example: The class declaration "class A" is equivalent to "class A extends Object".

2. Inheritance of Java subclasses

A class has two important members: member variables and methods. Some of the members of the subclass are declared and defined by the subclass itself, and the other part is inherited from its parent class. The subclass inherits the member variable of the parent class as one of its own member variables, as if the member variable is directly declared in the subclass, and can be operated by any instance method defined in the subclass itself. The subclass inherits the method of the parent class as one of its own methods, as if the method is directly defined in the subclass, and can be called by any instance method defined in the subclass itself.

Inheritance of subclasses and parent classes in the same package:

If the subclass and the parent class are in the same package, then the subclass naturally inherits the non-private member variables in its parent class as its own member variables, and also naturally inherits the non-private methods in the parent class as its own The access rights of methods, inherited member variables, or methods remain unchanged.

Inheritance where subclass and superclass are not in the same package:

If the subclass and the parent class are not in the same package, the member variables of private and friendly access rights in the parent class will not be inherited by the subclass, that is, the subclass only inherits the member variables and methods of protected and public access rights in the parent class as Member variables and methods of subclasses.

Further explanation about protected:

The protected member variables and methods in a class A can be inherited by its descendants. For example, if B is a subclass of A, C is a subclass of B, and D is a subclass of C, then B, C, and D classes all inherit protected member variables and methods of class A.

If an object is created in D itself with the D class , then the object can always access the inherited or self-defined protected variables and protected methods through the "." operator, but if it is in another class, such as in Other Class D is used to create an object object in the class, and the permission of the object to access protected variables and protected methods through the "." operator is as follows:

  1. For the protected member variables and methods declared by the subclass D, as long as the Other class and the D class are in the same package, the object object can access these protected member variables and methods.

  2. For the protected member variables or protected methods inherited by the subclass D from the parent class, it needs to be traced back to the "ancestor" class where these protected member variables or methods are located, for example, it may be class A, as long as the Other class and the A class are in the same package , The object object can access the inherited protected variables and protected methods.

3. Java subclasses and objects

When using the subclass constructor to create an object of a subclass, not only the member variables declared in the subclass are allocated memory, but also the member variables of the parent class are also allocated memory space, but only the part inherited by the subclass Member variables act as variables assigned to subclass objects.

That is to say, although the private member variable in the parent class is allocated memory space, it is not a variable of the subclass object; similarly, if the subclass and the parent class are not in the same package, although the friendly member variable of the parent class allocates memory space , but also as a variable of the subclass object.

At this point, we more or less feel that some memory seems to be wasted when the subclass creates the object. This is because when a subclass is used to create an object, the member variables of the parent class are also allocated memory space, but only part of it is used as a variable assigned to the subclass object. For example: Although the private member variables in the parent class are allocated memory space, they are not used as variables of the subclass object. Of course, they are not variables of an object of the parent class, because we have not used the parent class to create any objects at all. However, we should note that some methods in the subclass are inherited from the parent class, but these methods can operate on these uninherited variables.

For example: the object of the subclass ChinaPeople calls the inherited method to operate the variable that is not inherited by the subclass but has allocated memory space.

class People {
    
    
    private int averHeight = 168;
    public int getAverHeight() {
    
    
        return averHeight;
    }
}
class ChinaPeople extends People {
    
    
    int height;
    public void setHeight(int h) {
    
    
        //height = h+averHeight; //非法,子类没有继承averHeight
        height = h;
    }
    public int getHeight() {
    
    
        return height;
    }
}
public class Main
    public static void main(String args[]) {
    
    
        ChinaPeople zhangSan = new ChinaPeople();
        System.out.println("子类对象未继承的averageHeight的值是:"+zhangSan.getAverHeight ());
        zhangSan.setHeight(180);
        System.out.println("子类对象的实例变量height的值是:"+zhangSan.getHeight());
    }

insert image description here

Fourth, the hiding of Java member variables and method rewriting

When writing a subclass, we can still declare member variables. A special case is that the name of the declared member variable is the same as the name of the member variable inherited from the parent class, and the declared type can be different . In this case Next, the subclass will hide the inherited member variables .

The characteristics of subclass hidden inherited member variables are as follows:

(1) The subclass object and the method operation defined by the subclass itself refer to the member variable redeclared by the subclass with the same name as the parent class.

(2) The subclass object can still call the method inherited from the parent class to operate the member variable hidden by the subclass, that is to say, the member variable operated by the method inherited by the subclass must be the member variable inherited or hidden by the subclass.

Note:
The methods inherited by subclasses can only operate on member variables inherited and hidden by subclasses. The newly defined methods of the subclass can operate the member variables inherited by the subclass and newly declared by the subclass, but cannot operate the hidden member variables of the subclass .

Subclasses can hide inherited methods by rewriting, and method rewriting is also called method overriding. If a subclass can inherit a method of the parent class, then the subclass has the right to override this method. Method rewriting refers to defining a method in a subclass, the type of this method is the same as the type of the method of the parent class or a subtype of the method type of the parent class, and the name of the method, the number of parameters, the type of the parameters and The method of the parent class is exactly the same. The method defined by the subclass in this way is called the method overridden by the subclass, and is not a new method.

Subclasses can hide inherited methods through method rewriting, and change the state and behavior of the parent class to their own state and behavior. If the method f() of the parent class can be inherited by the subclass, the subclass has the right to rewrite f(), once the subclass rewrites the method f() of the parent class, the inherited method f() is hidden, then the subclass The method f() called by the class object must call the rewritten method f(). If the subclass does not override, but inherits the method f() of the parent class, then of course the object created by the subclass can call the f() method, but the behavior of the method f() is the same as that of the parent class.

Overridden methods can operate inherited member variables, call inherited methods, and can also operate newly declared member variables of subclasses and call other newly defined methods, but cannot operate member variables and methods hidden by subclasses. If a subclass wants to use a hidden method or member variable, the keyword super must be used.

Notice:

When rewriting the method of the parent class, it is not allowed to reduce the access rights of the method, but the access rights can be increased. The order of access restriction modifiers from high to low access rights is: public, protected, friendly, private. For example: the method f of the parent class is rewritten by the subclass, and the access right of this method in the parent class is protected level, and the level lower than protected is not allowed when the subclass is rewritten.

5. Java super keyword

Use super to manipulate hidden member variables and methods

Once the subclass hides the inherited member variable, the object created by the subclass will no longer own the variable, and the variable will be owned by the keyword super. Similarly, once the subclass hides the inherited method, the object created by the subclass will be The hidden method cannot be called, and the method is called by the keyword super. Therefore, if you want to use member variables or methods hidden by the subclass in the subclass, you need to use the keyword super.

Notice:

When super calls a hidden method, the member variables appearing in the method are member variables hidden by the subclass or inherited member variables.

Use super to call the constructor of the parent class

When using a subclass constructor to create an object of a subclass, the subclass constructor always calls a constructor of the parent class first , that is, if the subclass constructor does not explicitly indicate the use of the parent class Which construction method, the subclass calls the construction method of the parent class without parameters.

Since the subclass does not inherit the construction method of the parent class, the subclass needs to use super in its construction method to call the construction method of the parent class, and super must be the first statement in the construction method of the subclass, that is, if in the subclass In the construction method, if the super keyword is not clearly written to call a certain construction method of the parent class, then the default is:

super ();

6. Java final keyword

The final keyword can modify local variables in classes, member variables, and methods . You can use the keyword final to declare a class as a final class, and a final class cannot be inherited, that is, it cannot have subclasses.

For example:

final class A {
    
    
}

A is a final class, and no class will be allowed to be declared as a subclass of A. Generally, some classes are modified as final classes for security reasons. For example: the String class provided by Java in the java.lang package is very important for the normal operation of the compiler and interpreter. Java does not allow user programs to extend the String class, so Java modifies it as a final class.

If a method in the parent class is modified with final, then this method does not allow subclasses to override, that is, subclasses are not allowed to hide final methods that can be inherited.

If a member variable or local variable is modified as final, it is a constant. Since constants are not allowed to change during operation, there is no default value for constants when they are declared, which requires the program to specify the value of the constant when declaring the constant.

7. Upcast object of Java object

We know that tigers are animals. If the animal class is the parent class of the tiger class, it should be noted that when the tiger is an animal, the tiger will lose the unique attributes and functions of the tiger. From the perspective of human thinking, saying "a tiger is an animal" belongs to the upward thinking method, which is similar to the upward transformation object in the Java language.

Assuming that the Animal class is the parent class of the Tiger class, when creating an object with a subclass and putting the reference of this object into the object of the parent class , for example:

Animal a;
a = new Tiger();
Animal a;
Tiger b=new Tiger();
a = b;

At this time, calling object a an upcast object of object b is like saying "a tiger is an animal". The subclass is responsible for creating the entity of the object's upcast object, but the upcast object will lose some properties and functions of the original object.

Upcast objects have the following characteristics:

insert image description here(1) The transformation object cannot operate the member variables newly added by the subclass, and cannot call the methods newly added by the subclass.

(2) Upcast objects can access member variables inherited or hidden by subclasses, and can also call methods inherited by subclasses or instance methods overridden by subclasses. Upcast objects operate methods inherited by subclasses or instance methods overridden by subclasses, which are equivalent to subclass objects calling these methods. Therefore, if the subclass rewrites an instance method of the parent class, when the object's upcast object calls this instance method, it must call the instance method rewritten by the subclass.

Notice:

(1) Do not confuse the object created by the parent class with the upcast object of the subclass object.

(2) The upcast object of the object can be forcibly converted to a subclass object. At this time, the subclass object has all the attributes and functions of the subclass.

(3) The reference of the object created by the parent class cannot be assigned to the object declared by the subclass, for example: you cannot say "people are Chinese".

Eight, Java inheritance and polymorphism

We all know that "mammals have many kinds of calls", such as: "roar", "howl", "woof", "meow", etc. This is the polymorphism of calls.

Then when a class has many subclasses, and these subclasses override a method in the parent class, when we put the reference of the object created by the subclass into an object of the parent class, we get the An upcast object of an object. At this time, the upcast object may have polymorphism when calling this method, because different subclasses may produce different behaviors when rewriting the parent class method.

For example: when the upcast object of the dog class calls the "bark" method, the behavior is "bark", while the upcast object of the cat class calls the "bark" method, and the behavior is "meow" and so on.

Polymorphism means that when a method of a parent class is overridden by its subclasses, each can generate its own functional behavior.

For example:

class 动物 {
    
    
    void cry() {
    
    
    }
}
classextends 动物 {
    
    
    void cry() {
    
    
        System.out.println("wangwang");
    }
}
classextends 动物 {
    
    
    void cry() {
    
    
        System.out.println("miaomiao");
    }
}
public class Main {
    
    
    public static void main(String args[]) {
    
    
        动物 animal;
        animal = new();
        animal.cry();
        animal = new();
        animal.cry();
    }
}

insert image description here

Nine, Java abstract class and abstract method

  1. abstract class

We call the class modified with the keyword abstract an abstract class, that is, an abstract class , for example:

abstract class A {
    
    
}
  1. abstract method

We call the method modified with the keyword abstract the abstract method, that is, the abstract method , for example:

abstract int max(int x,int y);

Note:
1) For the abstract method, only declaration is allowed, no implementation is allowed, that is, there is no method body, and it is not allowed to use final and abstract to modify a method or class at the same time, and it is not allowed to use static to modify the abstract method, that is, the abstract method must be an instance method.

2) There can be abstract methods in abstract classes, and there can also be non-abstract methods, but non- abstract classes cannot have abstract methods.

For example: the max() method in class A is an abstract method, and the min() method is an ordinary method (non-abstract method).

abstract class A {
    
    
    abstract int max(int x,int y);
    int min(int x,int y) {
    
    
        return x<y?x:y;
    }
}

For abstract classes, the new operator cannot be used to create objects of this class. If a non-abstract class is a subclass of an abstract class, then it must rewrite the abstract method of the parent class and give the method body, which is not The reason for allowing both final and abstract to decorate a method or class at the same time.

We can use the abstract class to declare an object. Although the object cannot be created using the new operator, the object can become an upcast object of its subclass object, so that the object can call methods overridden by the subclass.

Note : an abstract class may not have an abstract method. If an abstract class is a subclass of an abstract class, it can either rewrite the abstract method of the parent class or inherit the abstract method of the parent class.

The study of this chapter will let you understand the inheritance of classes in java classes and how to call them correctly.

Learn from "https://www.dotcpp.com"

Summarize

Reading and friendship save our decaying souls.
I've always felt that giving a book is giving a fragment of my soul to a friend. If you can get resonance, it is really a great blessing in life!

Guess you like

Origin blog.csdn.net/weixin_51884452/article/details/130698353