[JavaSE] Object-oriented inheritance

inheritance concept

Inheritance mechanism: It is the most important means of object-oriented programming to make code reusable. It allows programmers to extend and add new functions while maintaining the characteristics of the original class. This generates a new class, which is called derivation. kind. Inheritance presents the hierarchical structure of object-oriented programming and reflects the cognitive process from simple to complex. The main problem that inheritance solves is: extraction of common features and realization of code reuse.

For example: dogs and cats are both animals, then we can extract the common content and then use the idea of ​​inheritance to achieve sharing.
Insert image description here
In the above illustration, both Dog and Cat inherit the Animal class. The Animal class is called the parent class/base class or super class. Dog and Cat can be called the subclass/derived class of Animal. After inheritance, the subclass can be duplicated. Using the members in the parent class, the subclass only needs to care about its own newly added members when implementing it.

Inherited syntax

In Java, if you want to express the inheritance relationship between classes, you need to use the extends keyword, as follows:

修饰符 class 子类 extends 父类 {
    
    
	// ...
}

So redesign the scene in the above picture using inheritance:
first create the Animal.java file

public class Animal{
    
    
	String name;
	int age;
	float weight;
	public void eat(){
    
    
		System.out.println(name + "正在吃饭");
	}
	public void sleep(){
    
    
		System.out.println(name + "正在睡觉");
	}
}

Then create the Dog.java file

public class Dog extends Animal{
    
    
	void bark(){
    
    
		System.out.println(name + "在汪汪叫~~~");
	}
}

Continue creating the Cat.Java file

public class Cat extends Animal{
    
    
	void mew(){
    
    
		System.out.println(name + "在喵喵叫~~~");
	}
}

Finally create the TestExtend.java file for testing

public class TestExtend {
    
    
	public static void main(String[] args) {
    
    
		Dog dog = new Dog();
		System.out.println(dog.name);
		System.out.println(dog.age);
		dog.eat();
		dog.sleep();
		dog. Bark();
	}
}

There are no member variables defined in the Dog class. The name and age attributes must be inherited from the parent class Animal. The eat() and sleep() methods accessed by Dog are also inherited from Animal.
Notice:

1. The subclass will inherit the member variables or member methods in the parent class to the subclass.
2. After the subclass inherits the parent class, it must add its own unique members to reflect the difference from the base class, otherwise there is no need to inherit.

Access to parent class members

The subclass and parent class do not have member variables with the same name

public class Base {
    
    
	int a;
	int b;
}
public class Derived extends Base{
    
    
	int c;
	public void method(){
    
    
		a = 10; // 访问从父类中继承下来的a
		b = 20; // 访问从父类中继承下来的b
		c = 30; // 访问子类自己的c
	}
}

Subclasses and parent classes have member variables with the same name

public class Base {
    
    
	int a;
	int b;
	int c;
}

public class Derived extends Base{
    
    
	int a; // 与父类中成员a同名,且类型相同
	char b; // 与父类中成员b同名,但类型不同
	public void method(){
    
    
		a = 100;
		b = 101; 
		c = 102; 
		d = 103;// 编译失败,因为父类和子类都没有定义成员变量b
	}
}
// 访问父类继承的a,还是子类自己的a?答案是自己的
// 访问父类继承的b,还是子类自己的b? 答案是自己的
// 子类没有c,访问的肯定是从父类继承下来的c

When accessing members in a subclass method or through a subclass object:

If the member variable to be accessed exists in a subclass, access your own member variable first. If the member variable being accessed does not exist in the subclass, it will be accessed inherited from the parent class. If the parent class is not defined, a compilation error will be reported. If the member variable being accessed has the same name as a member variable in the parent class, your own will be accessed first. Member variable access follows the principle of proximity. If you have one, you have priority. If not, you will find it in the parent class.

Member method names are different

// Base.java
public class Base {
    
    
	public void methodA(){
    
    
		System.out.println("Base中的methodA()");
	}
}
// Derived.java
public class Derived extends Base{
    
    
	public void methodB(){
    
    
		System.out.println("Derived中的methodB()方法");
	}
	public void methodC(){
    
    
		methodB(); // 访问子类自己的methodB()
		methodA(); // 访问父类继承的methodA()
		method(); // 编译失败,在整个继承体系中没有发现方法methodD()
	}
}

Summary: When a member method does not have the same name, when accessing the method in a subclass method or through a subclass object, you will access your own method first. If you do not find it yourself, you will look for it in the parent class. If it does not exist in the parent class, an error will be reported.

Member methods have the same name

// Base.java
public class Base {
    
    
	public void methodA(){
    
    
		System.out.println("Base中的methodA()");
	}
	public void methodB(){
    
    
		System.out.println("Base中的methodB()");
	}
}
// Derived.java
public class Derived extends Base{
    
    
	public void methodA(int a) {
    
    
		System.out.println("Derived中的method(int)方法");
	}
	public void methodB(){
    
    
		System.out.println("Derived中的methodB()方法");
	}
	public void methodC(){
    
    
		methodA(); // 没有传参,访问父类中的methodA()
		methodA(20); // 传递int参数,访问子类中的methodA(int)
		methodB(); // 直接访问,则永远访问到的都是子类中的methodB(),父类的无法访问到
	}
}

Notice:

When accessing methods with different names in the parent class and the subclass through the subclass object, the method is first searched in the subclass and accessed if found. Otherwise, the method is searched in the parent class and accessed if found. Otherwise, a compilation error is reported. When accessing the method with the same name of the parent class and the subclass through the subclass object, if the parameter list of the method with the same name of the parent class and the subclass is different (overloaded), select the appropriate method to access according to the parameters passed by the calling method, if not, an error will be reported.

super keyword

The main function of this keyword is to access members of the parent class in subclass methods.

// Base.java
public class Base {
    
    
	int a;
	int b;
	public void methodA(){
    
    
		System.out.println("Base中的methodA()");
	}
	public void methodB(){
    
    
		System.out.println("Base中的methodB()");
	}
}
// Derived.java
public class Derived extends Base{
    
    
	int a; 
	char b; 
	public void methodA(int a) {
    
    
		System.out.println("Derived中的method()方法");
	}
	public void methodB(){
    
    
		System.out.println("Derived中的methodB()方法");
	}
	public void methodC(){
    
    
		// 对于同名的成员变量,直接访问时,访问的都是子类的
		a = 100; // 等价于: this.a = 100;
		b = 101; // 等价于: this.b = 101;
		super.a = 200;
		super.b = 201;
		// 父类和子类中构成重载的方法,直接可以通过参数列表区分清访问父类还是子类方法
		methodA(); // 没有传参,访问父类中的methodA()
		methodA(20); // 传递int参数,访问子类中的methodA(int)
		// 如果在子类中要访问重写的父类方法,则需要借助super关键字
		methodB(); // 直接访问,则永远访问到的都是子类中的methodA(),父类的无法访问到
		super.methodB(); // 访问父类的methodB()
	}
}

Notice:

1. Super can only be used in non-static methods.
2. In the subclass method, access the member variables and methods of the parent class.

Subclass constructor

Father and son, father and son, there is father first and then son, that is: when constructing a subclass object, you need to call the parent class constructor first, and then execute the subclass constructor.

// Base.java
public class Base {
    
    
	public Base(){
    
    
		System.out.println("Base()");
	}
}
// Derived.java
public class Derived extends Base{
    
    
	public Derived(){
    
    
		// super(); // 注意子类构造方法中默认会调用父类的无参构造方	法:super(),
		// 用户没有写时,编译器会自动添加,而且super()必须是子类构造方法中第一条语句,并且只能出现一次
		System.out.println("Derived()");
	}
}
// Test.java
public class Test {
    
    
	public static void main(String[] args) {
    
    
		Derived d = new Derived();
	}
}
/*
* 运行的结果为:
* Base()
* Derived()
*/

In the subclass construction method, no code about the construction of the parent class is written, but when constructing the subclass object, the construction method of the parent class is executed first, and then the construction method of the subclass is executed, because: the members of the subclass object are It consists of two parts, the part inherited from the parent class and the newly added part of the subclass. When constructing a subclass object, first call the parent class's construction method to complete the construction of the members inherited from the parent class, and then call the subclass's own construction method to complete the initialization of the subclass's own newly added members .

Notice:

1. If the parent class explicitly defines a parameterless or default constructor, there is an implicit super() call by default in the first line of the subclass constructor, that is, the parent class constructor is called.
2. If the parent class constructor has parameters, the user needs to explicitly define the constructor for the subclass and select the appropriate parent class constructor to call in the subclass constructor, otherwise the compilation will fail.
3. In the subclass construction method, when super(...) calls the parent class construction, it must be the first statement in the subclass construction.
4.super(...) can only appear once in the subclass constructor, and cannot appear at the same time as this.

super and this

Both super and this can be used to access member methods: member variables and calling other member functions can both be used as the first statement of the constructor. So what is the difference between them?

Same point:

  • They are all keywords in Java.
  • It can only be used in non-static methods of a class to access non-static member methods and fields.
  • When called in a constructor, it must be the first statement in the constructor and cannot exist at the same time.

difference:

  • This is a reference to the current object, which is the object that calls the instance method. Super is equivalent to a reference to some members of the subclass object inherited from the parent class.
  • In non-static member methods, this is used to access methods and properties of this class, and super is used to access methods and properties inherited from the parent class.
  • In the constructor method: this(...) is used to call the constructor method of this class, and super(...) is used to call the constructor method of the parent class. The two calls cannot appear in the constructor method at the same time.
  • There must be a call to super(...) in the constructor, and the compiler will increase it if the user does not write it, but this(...) will not increase if the user does not write it.

Inheritance method

Only the following inheritance methods are supported in Java:
Insert image description here

Guess you like

Origin blog.csdn.net/qq_58032742/article/details/132338646