Chapter 12 three object-oriented features of JavaSE topic - inheritance

Posted by satanclaus on Mon, 07 Feb 2022 11:41:51 +0100

1. Inheritance overview

  • Inheritance: solve code reuse. When multiple classes have the same attributes (variables) and methods, you can abstract the parent class from these classes and define the same attributes and methods in the parent class. All subclasses do not need to redefine these attributes and methods, but only need to inherit the parent class through extensions

(1) Inheritance grammar

class Subclass extends Parent class{
}

/*
1,The subclass will automatically have the properties and methods defined by the parent class;
2,The parent class is also called super class and base class;
3,Subclasses are also called derived classes
*/
  • Inheritance diagram

(2) Introduction to inheritance

  • The contents are as follows:

① Create parent class

package com.taobao;

public class Person {
    public String name;     //Public name
    private int age;        //age privatization
    private double salary;  //..

    //alt+insert


    public Person() {
    }

    public Person(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;

        //Write the set method in the constructor so that it can still be verified
        setSalary(salary);
        setName(name);
        setAge(age);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        //1. Adding data verification is equivalent to adding default logic
        if(name.length() >=2 && name.length()<=6) {
            this.name = name;
        } else {
            System.out.println("The length of the name is incorrect,Requires 2 to 6 characters, default name");
            this.name = "Youth re-enter";
        }
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age>=1 && age <= 120) {
            this.age = age;
        }else{
            System.out.println("Wrong age setting,Need in(1-120),Give default age 18");
            this.age = 18;    //Give a default age
        }
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
    //Write a method to return attribute information
    public String info(){
        return "Information is name =" + name + "age = " + age + "Salary is =" + salary;
    }
}

② Create subclasses

package com.taobao;

public class Man extends Person {

    public void testing(){
        System.out.println(name);
    }
}

③ Subclass of main method call

package com.taobao;

public class hello {
    public static void main(String[] args) {
        Man man = new Man();
        man.name = "Zhang San";
        man.testing();
    }
}
  • Operation results

2. Inheritance details

2.1. Subclasses inherit all properties and methods

① Non private properties and methods can be accessed directly in subclasses;

② Private properties and methods cannot be accessed directly in subclasses, but through public methods;

  • Example: the directory structure is as follows

(1) Parent class Person creation

public class Person {
    public String name;
    private double salary;  //..

    //alt+insert
    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
    //Write a public property and return a public information
    public String info(){
        return "Salary is =" + salary;
    }

    //Write a private method
    private void info2(){
        System.out.println("full name:" + name);
    }

    //callTest
    public void callInfo2(){
        info2();
    }
}

(2) The subclass Man inherits the parent class of Person

public class Man extends Person {

    public void testing(){
        System.out.println(name);
    }
}

(3) The main method uses subclasses

public class hello {
    public static void main(String[] args) {
        Man man = new Man();
        //1. Subclasses inherit non private properties - can be accessed directly
        man.name = "Zhang San";
        //2. Subclasses inherit private properties - provide public methods (get) to access properties through the parent class
        man.setSalary(1000);
        //3. Class inherits the public method of the parent class - you can access it directly
        System.out.println(man.info());
        //4. Subclasses inherit the private methods of the parent class - access private methods by providing public methods in the parent class
        man.callInfo2();
        //5. Methods that directly access subclasses
        man.testing();
    }
}
  • Operation results

2.2. The subclass must call the parent class constructor to complete the initialization of the parent class
  • When creating a subclass object, no matter which constructor of the subclass is used, the parameterless constructor of the parent class is always called by default

    • There is a super() in the parameterless constructor of the subclass by default, representing the parameterless constructor calling the parent class;
    • When creating a subclass object, no matter which constructor of the subclass is used, the parameterless constructor of the parent class is called by default
  • Example: the directory structure is as follows

① Create parent class

package com.taobao;

public class Person {
    //Parent constructor
    public Person() {
        System.out.println("Call the constructor of the parent class...");
    }
}

② Create subclasses

package com.taobao;

public class Man extends Person {
    //Subclass constructor
    public Man() {
        //super();                 // By default, the parameterless constructor of the parent class is called
        System.out.println("Parameterless constructor for subclasses...");
    }
    public Man(String name){
        //super();
        System.out.println("parameter"+name);
    }
}

③ The main method creates a subclass object

package com.taobao;

public class hello {
    public static void main(String[] args) {
        Man man = new Man();
    }
}
  • Run result: create the parent class first and then the child class

2.3. The parent class does not provide a parameterless constructor
  • Note: you must use super in the constructor of the subclass to specify which constructor of the parent class is used to complete the initialization of the parent class, otherwise the compilation will not pass;

  • Example: the directory structure is as follows

① Create parent class

package com.taobao;

public class Person {
    public Person(String name) {
        System.out.println("Call the constructor of the parent class...");
    }
}

② Create subclasses

package com.taobao;

public class Man extends Person {

    public Man() {
        super("Zhang San");
        System.out.println("Parameterless constructor for subclasses...");;
    }
    public Man(String name) {
        super("Zhang San");
        System.out.println("Parameterized constructor of subclass...");;
    }
}

③ Create an object and call the parameterless constructor and the parameterless constructor of the subclass respectively

package com.taobao;

public class hello {
    public static void main(String[] args) {

        System.out.println("Call subclass parameterless constructor!");
        Man man = new Man();
        System.out.println("Call the parameterized constructor of the subclass!");
        Man man1 = new Man("lizhi");
    }
}
  • Operation results

  • matters needing attention
    • ① If you want to specify to call a constructor of the parent class, call it explicitly: Super (parameter list)
    • ② When using super, it needs to be placed in the first line of the constructor
    • ③ Both super() and this() can only be placed on the first line of the constructor, so the two methods cannot have the same constructor
    • ④ All classes in java are the parent class of object, and object is the base class of all classes;
    • ⑤ The call of the parent constructor is not limited to the direct parent class! The Object class (top-level parent class) will always be traced back to the top
    • ⑥ Subclasses inherit at most one parent class, that is, single inheritance in java: how to make class A inherit B and C, first let class B inherit C, and then let class A inherit B
    • ⑦ Inheritance cannot be abused, and the logical relationship between subclass and parent must meet is-a;

3. The essence of inheritance

  • example

(1) New class GradPa

package com.taobao;

public class GrandPa {
    String name = "grandpa";
    String hobby = "Travel";
}

(2) New subclass Father inherits GradPa class

package com.taobao;

public class Father extends GrandPa {
    String name = "Big head Dad";
    int age = 39;
}

(3) New subclass Son inherits Father

package com.taobao;

public class Son extends Father{
    String name = "Big head son";
}

(4) The main method creates a subclass object

package com.taobao;

public class hello {
    public static void main(String[] args) {
        Son son = new Son();
        System.out.println("call Son Subclass name:"+son.name);
        System.out.println("call Father Parent class age:"+son.age);
        System.out.println("call GrandPa Parent class hobby:"+son.hobby);
    }
}
  • Operation results

  • Attribute search order: returns information according to the search relationship
    • ① First, check whether the subclass has this attribute;
    • ② If the subclass has this attribute and can be accessed, the information is returned;
    • ③ If the child class does not have this attribute, it depends on whether the parent class has this attribute (if the parent class has this attribute and can access it, it returns information)
    • ④ If there is no parent class, continue to find the parent class and know the Object according to the rule in (3)
    • ⑤ If the private attribute is found upward, the get method is called;

4. super keyword

  • super: represents the reference of the parent class, which is used to access the properties, methods and constructors of the parent class
    • Explicitly call the parent class constructor in the subclass constructor
    • Access member methods and variables of the parent class.

(1) super basic syntax
① Access the property of the parent class, but cannot access the private property of the parent class;

super.attribute

② Access the method of the parent class, but cannot access the private method of the parent class;

super.Method name(parameter list)

③ Accessing the constructor of the parent class, but it can only be placed in the first sentence of the constructor, which conflicts with this;

super(parameter list)

(2) super calls the parent class constructor

When creating a subclass object, no matter which constructor of the subclass is used, the parameterless constructor of the parent class is always called by default,
    There is one in the parameterless constructor of subclass by default  super(),Represents the parameterless constructor that calls the parent class;
	When creating subclass objects,No matter which constructor of the subclass is used, the parameterless constructor of the parent class is called by default

(3) super calls the parent class attribute

  • When the parent and child classes have the same data members, the JVM may be ambiguous and need to be specified with super
  • Example 1 - find nearby without super
//1. Create parent class
class Person {
    int age = 12;
}

//2. Create subclasses
class Student extends Person {
    int age = 18;
    void display() {
        System.out.println("Student age:" + age);
    }
}

//3. Create test class
class Test {
    public static void main(String[] args) {
        Student stu = new Student();
        stu.display();
    }
}
  • Operation results

  • Example 2: add super to follow the parent class
//1. Create parent class
public class Person {
    int age = 12;
}

//2. Create subclasses
public class Student extends Person {
    int age = 18;
    void display() {
        System.out.println("Student age:" + super.age);
    }
}

//3. Create test class
public class Test {
    public static void main(String[] args) {
        Student stu = new Student();
        stu.display();
    }
}
  • Operation results

(4) super calls member methods

  • When the parent class and child class have the same method name, you can use the super keyword to access the methods of the parent class;

  • example:

//1. Create parent class
class Person {
    void message() {
        System.out.println("This is person class");
    }
}

//2. Create subclasses
class Student extends Person {
    void message() {
        System.out.println("This is student class");
    }
    void display() {
        message();        // Call the message method of the current class
        super.message();  // Call the message method of the parent class
    }
}

//3. main call subclass
class Test {
    public static void main(String args[]) {
        Student s = new Student();
        s.display();
    }
}
  • Operation results
    • Only the method message() is called, which means that the current class message() is called;
    • When using the super keyword, message() which is the parent class is called.

(5) The difference between super and this

Distinguishing pointsthissuper
1Access propertiesAccess the attribute in this class. If there is no such attribute in this class, continue to find it from the parent classDirect access to properties in the parent class
2Call methodAccess the method in this class. If there is no such method in this class, it will inherit from the parent classDirect access to methods in the parent class
3Invoking Constructors When calling this class constructor, it must be placed in the first line of the constructor**Directly call the parent class constructor, * * must be placed in the first line of the constructor
4specialRepresents the current objectAccessing parent objects in subclasses

5. Method override

(1) Overview of method rewriting

  • Method Rewriting: if a method in a subclass has the same name, return type and parameters as a method of the parent class, then we say that the method of the subclass overrides the method of the parent class;
//1. Create parent class
public class Animal {
    public  void cry(){
        System.out.println("Animal barking...");
    }
}

//2. Create subclasses
public class Dog extends Animal {
    public  void cry(){
        System.out.println("The dog barked...");
    }
}


//3. Subclass of main method call
public class OverrideMain {
    public static void main(String[] args) {
        //Demo method override
        Dog dog = new Dog();
        dog.cry();
    }
}
  • Operation results

(2) Method override details

I. the parameter and method name of the subclass method should be exactly the same as the parameter and method name of the parent method;

II. Return type of subclass method

  • The method return type of the parent class is the same;

  • The subclass of the return type of the parent class;

//Parent class
public object getInfo()

    
//Subclass
public String getInfo()

III. subclass methods cannot reduce the access rights of parent methods

//Parent class
void sayOk()

//Subclass
public void sayOk()

(3) The difference between method rewriting and method overloading

nameOccurrence rangeMethod nameparameter listReturn typeModifier
heavy loadThis categoryMust be the sameAt least one different type, number and orderNo requirementNo requirement
rewriteParent child classMust be the sameMust be the sameConsistent / parent-child classSubclass > parent access range

Topics: Java