2021-03-08

Object Oriented Basics-Inheritance

1. Inheritance

When the same attributes and behaviors exist in multiple classes, these contents are extracted into a single class, so there is no need to define these attributes and behaviors in multiple classes, and only need to form a certain relationship with the extracted class.
Among them, multiple classes can be called subclasses or derived classes ; the class extracted from multiple classes is called a parent class , a superclass, or a base class .

1.1 Benefits of inheritance:

  • Improve code reusability .
  • Improve code scalability .
  • The relationship between class and class is the prerequisite for learning polymorphism .
    By extendskeyword, you can declare a subclass inherits another parent class is defined in the following format:
【修饰符】 class 父类 {
    
    
	...
}

【修饰符】 class 子类 extends 父类 {
    
    
	...
}

Inheritance demonstration, the code is as follows:

/*
 * 定义动物类Animal,做为父类
 */
class Animal {
    
    
    // 定义name属性
	String name; 
    // 定义age属性
    int age;
	// 定义动物的吃东西方法
	public void eat() {
    
    
		System.out.println(age + "岁的" + name + "在吃东西");
	}
}

/*
 * 定义猫类Cat 继承 动物类Animal
 */
class Cat extends Animal {
    
    
	// 定义一个猫抓老鼠的方法catchMouse
	public void catchMouse() {
    
    
		System.out.println("抓老鼠");
	}
}

/*
 * 定义测试类
 */
public class ExtendDemo01 {
    
    
	public static void main(String[] args) {
    
    
        // 创建一个猫类对象
		Cat cat = new Cat()
      
        // 为该猫类对象的name属性进行赋值
		cat.name = "Tom";
      
      	// 为该猫类对象的age属性进行赋值
		cat.age = 2;
        
        // 调用该猫的catchMouse()方法
		cat.catchMouse();
		
      	// 调用该猫继承来的eat()方法
      	cat.eat();
	}
}

演示结果:
抓老鼠
2岁的Tom在吃东西

2. Inheritance feature one: member variables

2. 1 privatization of parent class member variables (private)

  • The members of the parent class, whether public or private, will be inherited by the subclass.
  • Although the child class inherits the private members of the parent class, the child class cannot directly access the inherited private members, and can be accessed through the inherited get/set methods.

code show as below:

/*
 * 定义动物类Animal,做为父类
 */
class Animal {
    
    
    // 定义name属性
	private String name; 
    // 定义age属性
    public int age;
	// 定义动物的吃东西方法
	public void eat() {
    
    
		System.out.println(age + "岁的" + name + "在吃东西");
	}
}

/*
 * 定义猫类Cat 继承 动物类Animal
 */
class Cat extends Animal {
    
    
	// 定义一个猫抓老鼠的方法catchMouse
	public void catchMouse() {
    
    
		System.out.println("抓老鼠");
	}
}

/*
 * 定义测试类
 */
public class ExtendDemo01 {
    
    
	public static void main(String[] args) {
    
    
        // 创建一个猫类对象
		Cat cat = new Cat()
      
        // 为该猫类对象的name属性进行赋值
		//cat.name = "Tom";// 编译报错
      
      	// 为该猫类对象的age属性进行赋值
		cat.age = 2;
        
        // 调用该猫的catchMouse()方法
		cat.catchMouse();
		
      	// 调用该猫继承来的eat()方法
      	cat.eat();
	}
}

2.2 The same name of the parent and child class member variables

(1) When the member variables of the parent class are privatized, they cannot be directly accessed in the child class, so whether the same name is not affected. If you want to access the private member variables of the parent class, you can only use the get/set of the parent class Method access

(2) When the member variables of the parent class are not private, they can be directly accessed in the child class, so if there are duplicate names, you need to add "super." to distinguish.

Use format:


super.父类成员变量名

3. The second characteristic of inheritance: member method

We say that all methods of the parent class will be inherited by subclasses, but when a method is inherited to the subclass, the subclass feels that the original implementation of the parent class is not suitable for the subclass. What should we do? We can rewrite the method (Override)

3.1 Method rewriting

1.@Override: written on the method, used to check whether it is valid and correct to overwrite. Even if this annotation is not written, as long as it meets the requirements, it is the correct way to overwrite and rewrite. Suggest to keep

2. It must be ensured that the method names and parameter lists are the same between the parent and child classes.
3. The return value type of the subclass method must be [less than or equal to] the return value type of the parent method (less than is actually its subclass, for example: Student <Person).

Note: If the return value type is the basic data type and void, it must be the same

4. The permission of the subclass method must be [greater than or equal to] the permission modifier of the parent method.
Small extension tip: public> protected> default> private

5. Several special methods cannot be rewritten

  • Static methods cannot be overridden
  • Private methods that are not visible in subclasses cannot be overridden
  • final methods cannot be overridden

3.2 Method overload

For the Son class, there are two print methods, a parameter list is (int i), and a parameter list (int i, int j)

4. The third characteristic of inheritance: construction method

When there are relationships between classes, what are the effects of the construction methods in each class?

First of all, we have to recall two things, the definition format and role of the construction method.

  1. The name of the constructor is consistent with the name of the class.

    Therefore, the subclass cannot inherit the construction method of the parent class.

  2. The role of the constructor is to initialize instance variables, and the subclass will inherit all member variables from the parent class

    Therefore, in the initialization process of the subclass, the initialization action of the parent class must be executed first. There is one by default in the subclass's construction method super(), which means that the instance initialization method of the parent class is called, and the member variables of the parent class are initialized before they can be used by the subclass. code show as below:

class Fu {
    
    
  private int n;
  Fu(){
    
    
    System.out.println("Fu()");
  }
}
class Zi extends Fu {
    
    
  Zi(){
    
    
    // super(),调用父类构造方法
    super();
    System.out.println("Zi()");
  }  
}
public class ExtendsDemo07{
    
    
  public static void main (String args[]){
    
    
    Zi zi = new Zi();
  }
}
输出结果:
Fu()
Zi()

in conclusion:

The instantiation of the subclass object must first complete the instance initialization of the member variables inherited from the parent class. This process is completed by calling the instance initialization method of the parent class.

  • super(): Indicates that the parameterless instance initialization method of the parent class is called, and the parent class must have a parameterless structure, and it can be omitted.
  • super (argument list): means to call the parameterized instance initialization method of the parent class. When the parent class has no parameterless construction, the first line of the constructor of the subclass must write super (argument list) to clarify which one of the parent class is called Parameter construction (in fact, the initial method of the instance corresponding to the constructor is called)
  • Both super() and super (argument list) can only appear in the first line of the subclass constructor

5. The fourth characteristic of inheritance: single inheritance restriction

Java only supports single inheritance, not multiple inheritance.

//一个类只能有一个父类,不可以有多个父类。
class C extends A{
    
    } 	//ok
class C extends A,B...	//error

Java supports multiple inheritance (inheritance system).

class A{
    
    }
class B extends A{
    
    }
class C extends B{
    
    }

6. this and super keywords

6.1 The meaning of this

this代表当前对象

6.2 Where to use this

  • this in the code block and constructor related to instance initialization: represents the instance object being created, that is, who is new, and this represents who
  • This in a non-static instance method: represents the object that calls the method, that is, who is calling, this represents who.
  • this cannot appear in static code blocks and static methods

6.3 Format of this

(1) this. member variable name

  • When the local variable of the method has the same name as the member variable of the current object, you can add this. in front of the member variable. If there is no problem with the same name, you can omit this.
  • This. member variable will be searched from the list of member variables declared by this class first, if not found, it will go to the list of member variables inherited from the parent class and still visible in the child class.

(2) this. member method

  • When calling the member method of the current object, you can add "this." or omit it. It is omitted in actual development.
  • The member methods of the current object are first searched from the list of member methods declared by this class. If it is not found, it will be searched in the list of member methods inherited from the parent class that are still visible in the child class.

(3) this () or this (list of actual parameters)

  • Only call other constructors of this class

  • Must be in the first line of the constructor

  • If n constructors are declared in a class, at most n-1 constructors use "this([argument list])", otherwise an endless loop of recursive calls will occur

7. Super keyword

7.1 The meaning of super

super represents the reference from the parent class in the current object

7.2 Prerequisites for using super

  • Refer to the xx of the parent class through super, which are still visible in the child class
  • Cannot use super in static code blocks and static methods

7.3 Use format of super

super. member variable
super. member method
super() or super (argument list)

8. Member variable initialization

8.1 Member variables have default values

Insert picture description here

8.2 Explicit assignment

public class Student{
    
    
    public static final String COUNTRY = "中华人民共和国";
	private static String school = "尚硅谷";
	private String name;
	private char gender = '男';
}

8.3 Code block

Static initialization block: initialize for static variables.
Instance initialization: initialize for instance variables.
Static initialization block: invoked and executed by the class loader when the class is initialized. The static initialization of each class will only be executed once, which is earlier than the creation of the instance object.

Instance initialization block: automatically executed every time an instance object is new, and executed once for every new object.

8.4 Constructor

We found that the explicit assignment and instance initialization blocks initialize the instance variables of each instance object to the same value, so what if we want different instance objects to be initialized to different values? At this point, we can consider using the constructor, and the creator of the object decides what value to assign to the instance variable of the current object when the object is new.

Note: The constructor is only initialized for instance variables, not for static class variables

Initialize the instance variable, and the creator of the object determines what value to assign to the instance variable of the current object when the object is new.

Guess you like

Origin blog.csdn.net/qq_37698495/article/details/114553134