Java Inheritance (Super Detailed Explanation)

Table of contents

1. Inheritance

1.1 Inheritance Overview

1.2 Advantages and disadvantages of inheritance

1.3 Access characteristics of variables in inheritance

 1.4 super

1.5 Access characteristics of constructors in inheritance

 1.6 Access characteristics of member methods in inheritance

 1.7 Method rewriting

 1.8 Precautions for method rewriting

1.9 Precautions for inheritance in java


1. Inheritance

1.1 Inheritance Overview

Inheritance is one of the three major characteristics of object-oriented. It can make the subclass have the properties and methods of the parent class, and can also redefine and add properties and methods in the subclass.

Inheritance refers to extending functions and creating new types based on the original class.

  • The essence of inheritance is the abstraction of a certain group of classes, so as to achieve better modeling of the real world.
  • Classes in JAVA only have single inheritance, no multiple inheritance!
  • Inheritance is a relationship between classes and classes. In addition, the relationship between classes and classes also includes dependency, composition, aggregation and so on.
  • There are two classes in the inheritance relationship, one is the subclass (derived class), and the other is the parent class (base class). The subclass inherits the parent class, using the keyword extends to represent.
  • In a sense, there should be an "is a" relationship between the subclass and the parent class.
  • extends means "extended", and the subclass is the extension of the parent class.

Inherited format:

  • Format: public class subclass name extends parent class name{}
  • For example: public class Zi extends Fu {}
  • Fu: is the parent class, also known as base class, super class
  • Zi: is a subclass, also known as a derived class

Inherit the characteristics of subclasses:

The subclass can have the content of the parent class, and the subclass can also have its own unique content.

For example: create a parent class Person

// 父类
public class Person {
    //public 公共的
    public int money = 1_0000_0000;
    public void say(){
        System.out.println("说话");
    }
 
}

Create a subclass Student

//student is person
//Teacher student也叫派生类或者子类
//子类可以继承父类的所有方法
public class Student extends Person{
 
}

Create a test Application class

public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        student.say();
        System.out.println(student.money);
    }
}

result:

 

1.2 Advantages and disadvantages of inheritance

Inheritance benefits:

  • Sharing data and methods
  • Improved code reusability (multiple classes with the same members can be placed in the same class)
  • Improve the maintainability of the code (if the code of the method needs to be modified, just modify one place)
  • Improved code scalability

Inheritance Disadvantages

  • Inheritance creates a relationship between classes, and the coupling of classes is enhanced. When the parent class changes, the implementation of the subclass has to follow the changes, weakening the independence of the subclass

1.3 Access characteristics of variables in inheritance

Access a variable in a subclass method

First search in the subclass local scope, if not, then search in the subclass member scope, and finally in the parent class member scope, if there is none, report an error (regardless of the father's father...).

For example: create a parent class Fu

public class Fu {
	public int age = 10;
}

Create a subclass Zi

public class Zi extends Fu {
	public int heigth = 180;
	public int age = 20;// 若果没有这句,和下面那句,输入的是10
	public void show() {
		int age = 30;// 若果没有这句,输入的是20
		System.out.println(age);
		System.out.println(heigth);
	}
}

Create a test class Test

public class Test {
	public static void main(String[] args) {
		// 创建对象调用方法
		Zi z = new Zi();
		z.show();
	}
}

result:

 1.4 super

The usage of the super keyword is similar to that of the this keyword

  • this: represents the reference of this class object (the this keyword points to the object that calls the method. Generally, we use the this keyword in the current class, so we often say that this represents the reference of this class object)
  • super: represents the identity of the parent class storage space (can be understood as a parent class object reference)
keywords access member variables access constructor access member method
this this.Member variable
Access the member variable of this class
this(...)
accesses the constructor of this class
this.Member method(...)
accesses the member methods of this class
super super.Member variables
access parent class member variables
super(...)
accesses the parent class constructor
super, member method(...)
access parent class member method

For example: define a parent class Fu

public class Fu {
	public int age = 10;

}

Define a subclass Zi


public class Zi extends Fu {
	public int age = 20;

	public void show() {
		int age = 30;
		System.out.println(age); // 30
		// 访问本类中的成员变量age
		System.out.println(this.age);
		// 访问Fu类中的成员变量age
		System.out.println(super.age);
	}
}

Test: Test

public class Test {
	public static void main(String[] args) {
		Zi z = new Zi();
		z.show();
	}
}

result:

1.5 Access characteristics of constructors in inheritance

All constructors in the subclass will access the parameterless constructor in the parent class by default.

  1. Because the subclass will inherit the data in the parent class, and may also use the data of the parent class. Therefore, before the subclass is initialized, the initialization of the parent class data must be completed first.
  2. The first statement of each subclass constructor defaults to: super()

 For example: create a parent class Fu

public class Fu {
	public Fu() {
		System.out.println("Fu中无参构造方法被调用");
	}

	public Fu(int age) {
		System.out.println("Fu中带参构造方法被调用");
	}
}

Create a subclass Zi


public class Zi extends Fu {
	public Zi() {
		// super();
		System.out.println("Zi中无参构造方法被调用");
	}

	public Zi(int age) {
		// super();
		System.out.println("Zi中带参构造方法被调用");
	}
}

Test: Test

public class Test {
	public static void main(String[] args) {
		Zi z = new Zi();
		System.out.println("-------------------");
		Zi zi = new Zi(18);
	}
}

result:

 What should I do if there is no no-argument construction method in the parent class, but only a parameter construction method?

  1. By using the super keyword to explicitly call the constructor with parameters of the parent class
  2. Provide a parameterless constructor in the parent class
  3. Recommendation: Give yourself a no-argument construction method

For example: create a parent class Fu

public class Fu {
	// public Fu() {
	// System.out.println("Fu中无参构造方法被调用");
	// }

	public Fu(int age) {
		System.out.println("Fu中带参构造方法被调用");
	}
}

Create a subclass Zi

public class Zi extends Fu {
	public Zi() {
		super(18);
		System.out.println("Zi中无参构造方法被调用");
	}

	public Zi(int age) {
		super(18);
		System.out.println("Zi中带参构造方法被调用");
	}
}

Test: Test

public class Test {
	public static void main(String[] args) {
		Zi z = new Zi();
		System.out.println("-------------------");
		Zi zi = new Zi(18);
	}
}

result:

 1.6 Access characteristics of member methods in inheritance

Access a method through a subclass object:

First search in the member range of the subclass, if you can’t find it, look in the member range of the parent class, if there is none, report an error (regardless of the father’s father...)

For example: create a parent class Fu

public class Fu {
	public void show() {
		System.out.println("Fu中show()方法被调用");
	}
}

Create a subclass Zi

public class Zi extends Fu {
	public void method() {
		System.out.println("Zi中method()方法被调用");
	}

	public void show() {
		super.show();
		System.out.println("Zi中show()方法被调用");
	}
}

Test: Test

public class Test {
	public static void main(String[] args) {
		Zi z = new Zi();
		z.method();
		System.out.println("----------");
		z.show();
	}
}

result:

 1.7 Method rewriting

Overview of method rewriting: the method declaration in the subclass is exactly the same as that in the parent class
Application of method rewriting: when the subclass needs the functions of the parent class, and the subclass of the function body has its own unique content, it can rewrite the method in the parent class In this way, the functions of the parent class are inherited, and the specific content of the subclass is defined

@Override
is an annotation that helps us check the correctness of the method declaration of the overriding method

For example: define a mobile phone class Phone

public class Phone {
	public void call(String name) {
		System.out.println("给" + name + "打电话");
	}
}

Define a new mobile phone class NewPhone

public class NewPhone extends Phone {
	public void call(String name) {
		System.out.println("开启视频功能");
		// System.out.println("给" + name + "打电话");
		super.call(name);
	}
}

Test: PersonTest 

public class PersonTest {
	public static void main(String[] args) {
		Phone p = new Phone();
		p.call("张三");
		System.out.println("--------");
		NewPhone np = new NewPhone();
		np.call("张三");
	}
}

result:

 1.8 Precautions for method rewriting

Private methods cannot be overridden (private members of the parent class cannot be inherited by subclasses)

Subclass method access rights cannot be lower (public>default>private)

1.9 Precautions for inheritance in java

Classes in Java only support single inheritance, not multiple inheritance

Classes in Java support multi-level inheritance

practise:

Example 1: Define the teacher class and the student class, and then write the code test; finally find the common content between the teacher class and the student class, extract a parent class and rewrite the code by inheritance, and test it

Define a public parent class Person

public class Person {
	private String name;
	private int age;

	public Person() {
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setAge(int age) {
		this.age = age;
	}
	public int getAge() {
		return age;
	}

}

Define a Student class

public class Student extends Person {

	public Student() {
	}

	public Student(String name, int age) {
		super(name, age);
	}
	public void studv() {
		System.out.println("好好学习,天天向上");
	}

}

Define a Teacher class

public class Teacher extends Person {
	public Teacher() {
	}

	public Teacher(String name, int age) {
		super(name, age);
	}
	public void teach() {
		System.out.println("金牌教师");
	}

}

Test: Test

public class Test {
	public static void main(String[] args) {
		Teacher t = new Teacher();

		t.setName("张三");
		t.setAge(50);
		System.out.println(t.getName() + "," + t.getAge());
		t.teach();

		Teacher te = new Teacher("李四", 55);
		System.out.println(te.getName() + "," + te.getAge());
		te.teach();
		System.out.println("---------------");


		Student s = new Student();

		s.setName("刘风");
		s.setAge(20);
		System.out.println(s.getName() + "," + s.getAge());
		s.studv();

		Student st = new Student("王凯", 18);
		System.out.println(st.getName() + "," + st.getAge());
		st.studv();
	}
}

result:

 Example 2: Please adopt the idea of ​​inheritance to realize the cases of cats and dogs, and test them in the test class

Define a Cat class

public class Cat extends Animal {
	public Cat() {
	}

	public Cat(String name, int age) {
		super(name, age);
	}

	public void CatMouse() {
		System.out.println("猫吃鱼");
	}
}

Define a Dog class

public class Dog extends Animal {
	public Dog() {
	}

	public Dog(String name, int age) {
		super(name, age);
	}

	public void DogMouse() {
		System.out.println("狗吃骨头");
	}

}

Define an Animal class

public class Animal {
	private String name;
	private int age;

	public Animal() {
	}

	public Animal(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setAge(int age) {
		this.age = age;
	}
	public int getAge() {
		return age;
	}
}

Test: Test

public class Test {
	public static void main(String[] args) {
		Cat c = new Cat();
		c.setName("狸花猫");
		c.setAge(10);
		System.out.println(c.getName() + "," + c.getAge());
		c.CatMouse();

		Cat ca = new Cat();
		ca.setName("橘猫");
		ca.setAge(5);
		System.out.println(ca.getName() + "," + ca.getAge());
		ca.CatMouse();
		System.out.println("--------");
		Dog d = new Dog();
		d.setName("中华田园犬");
		d.setAge(10);
		System.out.println(d.getName() + "," + d.getAge());
		d.DogMouse();

		Dog dog = new Dog();
		dog.setName("二哈");
		dog.setAge(5);
		System.out.println(dog.getName() + "," + dog.getAge());
		dog.DogMouse();
	}
}

result:

 

Guess you like

Origin blog.csdn.net/m0_52896041/article/details/131783158