Object oriented - inheritance

Posted by chuckjones on Sat, 20 Nov 2021 17:25:00 +0100

inherit

Inheritance is a cornerstone of java object-oriented programming technology because it allows the creation of hierarchical classes.

Inheritance is that a subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance domain and method 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.

Inheritance is one of the most prominent features of object-oriented
Inheritance is to derive a new class from an existing class. The new class can absorb the data properties and behaviors of the existing class and expand new capabilities
Java inheritance is a technology that builds new classes based on the definition of existing classes
The definition of a new class can add new data or new functions, or use the functions of the parent class, but it cannot selectively inherit the parent class (super class / base class)
This inheritance makes it easy to reuse the previous code, which can greatly shorten the development cycle and reduce the development cost
 

Inheritance format of class:

Class parent class {}

Class subclass extends parent class {}

Inheritance type: it should be noted that Java does not support multiple inheritance, but supports multiple inheritance.

 

  Benefits of inheritance:

(1) Improve the reusability of class code

(2) Improved code maintainability

(3) The relationship between classes is the premise of polymorphism (it is also a disadvantage of inheritance, and the coupling of classes is improved)

Inherited properties

  • Subclasses have non private properties and methods of the parent class.

  • Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.

  • Subclasses can implement the methods of the parent class in their own way, that is, override the methods of the parent class.

  • Java inheritance is single inheritance, but multiple inheritance is allowed. Single inheritance means that a subclass can only inherit one parent class. Multiple inheritance means, for example, class a inherits class B, and class B inherits class C. Therefore, according to the relationship, class C is the parent of class B, and class B is the parent of class A. This is a feature of Java inheritance different from C + + inheritance.

  • Inheritance can be realized by using the keywords extends and implements, and all classes inherit from java.lang.Object. When a class does not inherit the two keywords, it inherits object by default (this class is in   java.lang   Package, so you don't need it   import) ancestor class.

  • It improves the coupling between classes (the disadvantage of inheritance, the higher the coupling will cause the closer the connection between codes, the worse the code independence).

characteristic

  1. Use the extends keyword to represent inheritance relationships
  2. It is equivalent to the subclass copying the function of the parent class
  3. Java only supports single inheritance
  4. Inheritance can be passed on (a relationship like grandpa / son / grandson)
  5. The private members of the parent class will also be inherited, but because they are private and invisible, the child class cannot use the private resources of the parent class
  6. Inheritance is used to modify multiple functions. Subclasses can expand functions while having the functions of the parent class
  7. Like the relationship between is a nd a

Exercise: inherit the introductory case

package cn.tedu.oopextends;
/*This class is used as an introductory case for inheritance*/
public class ExtendsDemo {
    public static void main(String[] args) {
        //5. Create three class objects
        Animal a = new Animal();
        Cat c = new Cat();
        MiaoMiao m = new MiaoMiao();
        //6. Use object to call methods for testing
        a.eat();
        c.eat();//Dad can use grandpa's method
        m.eat();//Grandchildren can use grandpa's methods
        /*3.Inheritance also has transmissibility. Grandpa's function will be passed on to Dad, and dad's function will be passed on to grandchildren*/
    }
}

/*1.We use the extends keyword to establish the inheritance relationship between the subclass and the parent class. The format is: subclass extends parent class*/
/*2.java Only single inheritance is supported. A subclass can only have one parent class, but a parent class can have multiple subclasses*/
//1. Create grandpa class
class Animal{
    //4. Method of adding grandpa class
    public void eat(){
        //South is a shortcut for generating print statements
        System.out.println("Small animals Animal You can eat anything~");
    }
}
//2. Create father class and establish inheritance relationship with Animal class
/*6.Inheritance is the relationship between is and A. for example, a kitten is a small animal and Miao Miao is a kitten
* Inheritance requires that the subclass must be a subordinate type of the parent class, which is highly dependent and strongly coupled*/
class Cat extends Animal{
    //7. Define the attribute in the parent class -- member variable
    int a = 10;//General properties
    private int b = 100;//Private property
}
//3. Create grandchildren and establish inheritance relationship with Cat class
class MiaoMiao extends Cat{
    /*4.Subclasses can have their own unique methods to expand functions. They are better than the blue*/
    //8. Define methods unique to grandchildren
    public void studyJava(){
        System.out.println("Learning Java");
        /*5.After a subclass inherits the parent class, it can use all non private resources of the parent class
        * Note: this private resource cannot be used because the subclass is invisible, not because there is no inheritance
        * Because after the subclass inherits the parent class, it is equivalent to completely copying the functions of the parent class*/
        System.out.println(a);//Non private resources of the parent class can be used
        //System.out.println(b);// The private resources of the parent class cannot be used, and an error will be reported
    }
}


super

You can use this keyword to use the content of the parent class. Super represents a reference object of the parent class
Note: in the constructor, the calling position must be the first line

Method Override

  1. After inheritance, the child class has the function of the parent class
  2. In a subclass, you can add functions specific to the subclass or modify the original functions of the parent class
  3. When the signature of the method in the subclass is exactly the same as that of the parent class, overwrite / replication will occur
  4. Note: private methods of the parent class cannot be overridden
  5. Requirements for rewriting: two are the same, two are small and one is large
    Two same: the method name and parameter list should be completely consistent

Two hours:

The return value type of the subclass is less than or equal to the return value type of the parent class (note that this refers to the inheritance relationship, not the value size)
The exception thrown by the subclass is less than or equal to the exception thrown by the parent class method
First, the modifier permission of the subclass method should be greater than or equal to that of the overridden method of the parent class

  Usage of inheritance  

Use of member variables in the inheritance of super

package cn.tedu.oopextends;
/*Use of variables in test inheritance*/
public class TestExtends1 {
    public static void main(String[] args) {
        new Son().study();
        Father f = new Father();
    }
}

//1. Create parent class
class Father{
    //3. Create a member variable of the parent class
    int sum = 1;
    int count = 2;
}
//2. Create subclasses
class Son extends Father{
    //4. Create member variables of subclasses
    int sum = 10;
    //5. Common methods for creating subclasses
    public void study(){
        //6. Create local variables of subclasses
        int sum = 100;
        System.out.println("study hard and make progress every day");
        //7. Print the local variable sum of the subclass
        System.out.println(sum);//100
        //8. Print the member variable sum of the subclass
        System.out.println(this.sum);//10
        //9. Print the member variable count of the parent class
        System.out.println(count);//2
        //10. Print the member variable sum of the parent class
        /*When the parent class has the same name as the member variable of the child class, you can use super to specify the member variable of the parent class
        * We can regard super as the object of the parent class: Father super = new Father();*/
        System.out.println(super.sum);//1
    }
}

Use of construction methods in super inheritance

package cn.tedu.oopextends;
/*This class is used to test the use of construction methods in inheritance*/
/*1.When a subclass creates an object, it will call the constructor of the parent class first by default
  2.The reason is that super() exists in the first line of the constructor of the subclass by default -- indicating that the parameterless construction of the parent class is called
  3.When the parent class has no parameterless construction, other parameterless constructions of the parent class can be called through super (parameter)
    However, you cannot call the constructor of any parent class without selecting one
  4.Constructor cannot be inherited! Because of syntax: the constructor name is the class name, and a constructor with a parent class name cannot be written in a subclass
* */
public class TestExtends2 {
    public static void main(String[] args) {
        //6. Create subclass objects
        Son2 s = new Son2();
    }
}
//1. Define parent class
class Father2{
    //3. Create a parameterless construct of the parent class
//    public Father2(){
//        System.out.println("I'm a parameterless construct ~" of Father2);
//    }
    //4. Create a parameter containing construct of the parent class
    public Father2(String s){
        System.out.println("I am Father2 Parametric structure of"+s);
    }
}
//2. Define subclasses
class Son2 extends Father2{
    //5. Create parameterless construction of subclasses
    public Son2(){
        //super();// Call the function of parameterless construction of parent class
        super("Ha ha ha");
        System.out.println("I am Son2 No parameter structure!");
    }
}

Exercise: using member methods in inheritance

package cn.tedu.oopextends;
/*This class is used to test the use of methods in inheritance*/
public class TestExtends3 {
    public static void main(String[] args) {
        //4. Create subclass objects for testing
        Son3 s = new Son3();
        s.eat();//Subclass objects can call methods inherited from the parent class
        s.play();//Subclass objects can call methods inherited from the parent class
        s.studyJava();//Subclass objects call their own unique methods
        Father3 f = new Father3();
        f.play();
        f.eat();
    }
}
//1. Create parent class
class Father3{
    //3. Define common methods in the parent class
    public void eat(){
        System.out.println("Dad loves meat");
    }
    public void play(){
        System.out.println("Dad loves flying kites");
    }
}
//2. Create subclasses
@SuppressWarnings("LanguageDetectionInspection")
class Son3 extends Father3{
    //5. Create methods unique to subclasses
    public void studyJava(){
        System.out.println("Come on, learn Java And~");
    }

    //6. Method rewriting
    /*Override: when the subclass is not satisfied with the method of the parent class, it can override the method of the parent class
    * Rewriting grammar rules: two are the same, two are small and one is large
    * One: modifier permission of subclass method > = modifier permission of parent class method
      Two are the same: the method name is the same, and the parameter list is the same
      Two small: return value type of subclass method < = return value type of parent class method
      * The exception type thrown by the subclass method < = the exception type thrown by the parent method [this has not been learned, so don't worry]
      Note 1: if the return value type of the parent method is void, the return value type of the child method is also void
      Note 2: the size of the return value type here is not the size of the value, but the inheritance relationship
      * //Parent: int child: int
      * //Parent: int child: long not allowed
      * //Parent: Animal child: Animal/Cat/Dog... Yes
     */
    //Modifier return value type method name (parameter list) {method body}
    @Override/*This annotation is similar to a tag to mark that this is an overridden method*/
    public void play(){
        System.out.println("I want to play video games");
    }
    @Override
    public void eat(){
        System.out.println("My son likes vegetables");
    }

}

expand:

  The difference between Overload and Override

Overload: phenomenon in a class: in the same class, there are methods with the same method name and different parameter lists
Rewriting: it means that after the inheritance relationship is established, the subclass can override the method of the parent class if it is not satisfied with it, and follow the principle of "two in common, two small and one"
The meaning of overloading: it is convenient for the outside world to call methods. No matter what parameters are passed in, they can match the corresponding method with the same name
Meaning of Rewriting: modify and expand functions without modifying the source code (OCP principle: close for modification and open for expansion)
 

Topics: Java