Inheritance and polymorphism of Java

Keywords: Java

1, Inherit

1.1 definition of inheritance:

Inheritance refers to defining a new subclass based on the parent class. The subclass has the general characteristics of the parent class (general characteristics include non private attributes and behaviors). The subclass can add the characteristics that the original parent class does not have, define new attributes and behaviors, or rewrite some attributes and methods in the parent class to extend the functions of the class.

1.2 declaration and application of inheritance

1.2.1 declaration

Extends keyword: the subclass uses the extends keyword to inherit from the parent class.
Assuming that there is a parent class named Father and a Child class, the statement of the Child class inheriting the parent class is as follows:

public class Father{}//Define a parent class named Father

public class  Child extends Father{}//Define a subclass named Child that inherits from the Father class

1.2.2 application

Public members of the parent class can be used directly in derived classes, but private members cannot. The private class can only be accessed within the class that defines it. If you want to communicate with the private members of the parent class, you can only use the public method members inherited from the parent class.

package TestCome;

public class Father {
	public int a;//Public data, uninitialized
	private int x;//Private data
	private int y;
	protected int c;//Protected data
	protected int d;//Protected data
	public Father(int x,int y){
	this.x=x;//Use the this keyword to specify that the current parent object x is called
	this.y=y;//Use the this keyword to specify that the current parent object is called y
	public int getX(){return x;}
	public int getY(){return y;}

	public void  Over(){System.out.println("Father");}


package TestCome;

public class Child extends Father{
	private int z;//Add private data or attributes specific to subclasses
	public int a=1;//Initialize public data of parent class a
	public int getInt() {return c;}//Use protected members of the parent class directly c
	//Define constructor
	Child(int x,int y,int z){
	super(x,y);//Use the super keyword to specify to call the parent class constructor
	this.z=z;//Use this keyword to specify to call the current subclass object z
	//New subclass specific methods
	//public void setZ(int z) {this.z=z;}
	public int getZ(){return z;}

package TestCome;

public class Test{
	public static void main(String[] args){
		Child a1=new Child(1,2,3);
		System.out.printf("a1:(%d,%d,%d) \n",a1.getX(),a1.getY(),a1.getZ());
		System.out.printf("a1:(%d,%d,%d) \n",a1.getX(),a1.getY(),a1.getInt());//Parent protected member c in subclass
		System.out.printf("Protected object of parent class c:");
		System.out.print(a1.c);//Protected objects that use the parent class directly
		System.out.printf("Public object of parent class a:");
		System.out.print(a1.a);//Use the public object of the parent class directly

Save compilation run: place the mouse over the entire package to compile all classes

If a member is declared protected, the subclass that extends it can directly use the data member instead of calling it through the public member.
A subclass can only inherit from a single parent class, that is, single inheritance. However, a parent class can have multiple subclasses.

1.3 relationship between subclass and parent

(1) Subclasses automatically inherit the properties and methods of the parent class, but cannot inherit member variables and members with private access rights.

(2) Subclasses can define unique properties and methods.

(3) Override of methods in subclasses:

Method override: means that the method defined by the subclass and the method of the parent class have the same name, parameter list, return type and access modifier.
Method overwriting will hide the same name method of the parent class, that is, calling the method accelerate() in the subclass will no longer invoke the same name method accelerate() of the parent class, but the accelerate() that is rewritten in the subclass.

public class Vehicle{
	//This class is the parent class
	String type;
	String brand;
	int engineNum;
	String color;
	//Construction method
	public Vehicle(){
	this("Parent general purpose vehicle","Honda",2,"silver gray");
	public Vehicle(String type,String brand,int engineNum,String color){
	public void start(){
		System.out.println(type+brand+engineNum+"engine"+color+"Car start");
	public void accelerate(){

public class Bus extends Vehicle{
	int maxLoad;
	String busNo;
	//Construction method
	public Bus(){
	this(40,"8 road");
	public Bus(String type,String brand,int engineNum,String color,int maxLoad,String busNo){
	public Bus(int maxLoad,String busNo){
	public void accelerate(){//Method rewrite
		System.out.println("This is a subclass Bus Method overrides in");
	//Station reporting
	public void announceBusStop(){
	System.out.println(busNo+"Bus stop announcement");

public class Test{
	public static void main(String[] args){
		Vehicle vehicle=new Vehicle();  //Parent class
		//Vehicle vehicle = new vehicle ("parent general vehicle", "red flag", 2, "black");
		//Bus bus=new Bus();   // Subclass
		//Bus bus=new Bus(50);
		Bus bus=new Bus("Subclass bus","goddess",2,"white",50,"9 road");
		bus.announceBusStop();//Station reporting

(4) super keyword and this keyword

If the properties of the child class are the same as those of the parent class, there will be a hidden phenomenon. After hiding, if you need to use the member properties and member methods of the parent class, you can use the super keyword.

super.accelerate();//super refers to the parent object of the current object

If this keyword is used, it means to call the accelerate() method of the current object:

this.accelerate();//this refers to the current object

By using the super and this keywords, you can clearly distinguish whether you are calling a member of the current object or a member of the parent object.
In addition, when the variable defined in the method body or the formal parameter of the method is the same as the member variable name of the object, you must also use the this keyword to specify the member variable of the current object.

(5) Construction method of subclass

A subclass cannot inherit the construction method of the parent class. The construction method of the parent class is used to create the parent object. A subclass needs to define its own construction method to create a subclass object.
In the constructor of a subclass, the constructor of the parent class is called through the super keyword. When a subclass creates an object, it first creates a parent object and then a subclass object, so "super([parameter]);" must be the first statement of the subclass construction method. If this statement is omitted, the subclass will automatically call the parameterless construction method of the parent, for example,

super();//Call the parameterless constructor of the parent class
super(type,brand,engineNum,color);//Call the parameterized constructor of the parent class

If you need to call the constructor in the current class, use the this keyword, for example

this(40,"8 road");//Call the constructor with parameters in the current class

1.4 root class Object

In Java, all classes are directly or indirectly inherited from the java.lang.Object class. The Object class is the root class of all classes.
When you define a class without using the extends keyword, it means that the parent class of the defined class is the Object class by default. For the method of the root class, its subclasses can be called through inheritance.


  1. Private members, that is, private members.
    It can only be used inside the object and cannot be called directly by adding. To the reference name. Even if the class is extended, the derived class cannot directly use the private member of the parent class. The private member can only be called or set through the public method member provided by the parent class.
  2. Protected members, that is, protected members.
    After the members of the class are declared as protected members, the inherited class can use these members directly, but they can only be used inside the object or child objects, and cannot be called directly by external objects.
  3. Public members, that is, public members.

2, Polymorphism

2.1 definition of polymorphism

Polymorphism refers to the multiple implementation States declared by a method, that is, the coexistence of different methods with the same name in the program. If the caller uses the same method name, the system will call the relative method according to the specific situation, so as to realize different functional states. That is, one name, many methods.
Polymorphism is a feature with multiple forms of ability. Sometimes this feature can be used to improve the abstraction and simplicity of programs, as well as the scalability and maintainability of programs.
Classification of polymorphism:
Polymorphism can be divided into static polymorphism and dynamic polymorphism.
Static polymorphism refers to the polymorphism realized by method overloading in the same class. It is a compilation time polymorphism. The program will call the corresponding method according to different parameters. The compiler statically determines which overloaded method to call in the compilation stage. Static polymorphism is more efficient when the program is running.
Dynamic polymorphism refers to the polymorphism implemented by the method rewriting state between classes. It is runtime polymorphism. The system determines which rewriting method to call according to the type of the instance calling the method. Dynamic polymorphism is more flexible when the program is running.
Implementation of polymorphism:

		//Pseudo code: focus on analysis, not whether it runs successfully
		//Parent class
		public class Father{
			int drink(){
			return 0;
		public clsss Child extends Father{
			int drink(){
			Ststem.out.println("Child Rewritten drink()method");
			return 0;
		public static void main(String[] args){
		Father father=new Child();/**The system will analyze that the reference is a subclass type,
		*Therefore, the subclass method of the reference will be called
		//Call the drink() method overridden by the subclass Child

In addition to private attributes, subclasses have all the attributes of the parent class through inheritance. Therefore, subclass objects can be used instead of parent objects wherever they are required.
For an instance of a subclass, the runtime system will actually call which method and whether it overrides the parent class. If the subclass overrides the method of the parent class, the instance of the subclass will call the overridden method with the same name as the parent class. If the method of the parent class is not overridden, the method in the parent class will be called. That is, the parent class object can call the methods of the subclass by referring to the instance of the subclass.

3, Final and abstract classes

The class defined with the final keyword is called the final class. The final class cannot be inherited and has no subclasses. Once defined, a class commonly used to complete a convenient function does not need to be subclassed, so it is called the final version of the class.
Declaration format:

final class Class name{

Abstract class:
A class defined with the abstract keyword is called an abstract class. As long as there are abstract methods in a class, its class needs to be defined as an abstract class, but an abstract class can have no abstract methods.
Declaration format of abstract class:

[public] abstract class Class name{


Abstract classes can be inherited, but instances cannot be created.
Abstract methods show polymorphism in different subclasses - abstract classes provide a mechanism for separating method declaration from method implementation, that is, abstract methods with only method header but no method body can be declared, and the method body is implemented in subclasses.

public abstract class Computer{
	String brand;
	abstract void showBrand();

public class NoteBook extends Computer{
	void showBrand(){
	public static void main(String[] args){
		Computer computer=new NoteBook();//The object of the subclass is assigned to the variable of the abstract class,

Posted by baby on Tue, 05 Oct 2021 17:29:50 -0700