static keyword and inheritance -- > inheritance

1 origin of inheritance

Concept of inheritance

  • When multiple classes have the same features and behaviors, the same content can be extracted to form a public class, so that multiple classes can absorb the existing features and behaviors in the public class, and the mechanism that only needs to write their own unique features and behaviors in multiple types is called inheritance.

  • The extensions keyword is used in the Java language to represent inheritance relationships.

    • For example:

      Public class Worker extensions Person {} - indicates that the Worker class inherits from the Person class

      The Person class is called super class, parent class and base class.

      The Worker class is called derived class, subclass and child class.

  • Using inheritance improves the reusability, maintainability and expansibility of code, which is the prerequisite of polymorphism.

Characteristics of inheritance

  • Subclasses cannot inherit the constructor and private methods of the parent class, but private member variables can be inherited, but they cannot be accessed directly.

  • No matter how the subclass object is constructed, the parameterless construction method of the parent class will be automatically called to initialize the member variables inherited from the parent class, which is equivalent to adding the effect of code super() in the first line of the construction method.

  • The use of inheritance must meet the logical relationship: the subclass is a parent class, that is, inheritance cannot be abused.

  • The Java language only supports single inheritance, not multiple inheritance, that is, a subclass can only have one parent class, but a parent class can have multiple subclasses.

The concept of method rewriting

  • When the method inherited from the parent class does not meet the needs of the child class, you need to rewrite a method in the child class that is the same as the parent class to overwrite the version inherited from the parent class. This method is called method Override

Principle of method rewriting

  • The method name, parameter list and return value type are required to be the same. Subclass types are allowed to be returned from Java 5.
  • It is required that the access rights of methods cannot be reduced, but can be the same or larger.
  • Requires that the method cannot throw a larger exception (exception mechanism)
/*
    Programming the encapsulation of Person class
 */
public class Person {
	
	// 1. Privatize the member variable and use the private keyword to modify it
	private String name;
	private int age;
	//private boolean gender; //  Gender
	
	// 3. in the construction method, we call the set method to judge the reasonable value.
	public Person() {
		System.out.println("Person()");
	}
	public Person(String name, int age) {
		System.out.println("Person(String, int)");
		setName(name);
		setAge(age);
	}
	
	// 2. Provide public get and set methods and judge the reasonable value in the method body
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		if(age > 0 && age < 150) {
			this.age = age;
		} else {
			System.out.println("Age is unreasonable!!!");
		}
	}
	
	// Custom member method to print features
	public void show() {
		System.out.println("I am" + getName() + ",this year" + getAge() + "Years old!");
	}
	// Custom member methods describe the behavior
	public void eat(String food) {
		System.out.println(food + "Really delicious!");
	}
	// Custom member methods describe the behavior of entertainment
	public void play(String game) {
		System.out.println(game + "What fun!");
	}
}
/*
    Programmatically implement the Teacher class, which inherits from the Person class
 */
public class Teacher extends Person {   
	
}
/*
     Programming the test of Teacher class
 */
public class TeacherTest {
	
	public static void main(String[] args) {
		
		// 1. Use parameterless method to construct objects of Teacher type and print features
		Teacher t1 = new Teacher();
		t1.show(); // null 0
	}
}
Person()
I am null,I'm 0 years old!
/*
    The custom Worker class inherits from the Person class
 */
public class Worker extends Person {
	
	private int salary;
	
	public Worker() {
		super(); // It refers to calling the parameterless construction method of the parent class. If it is not added, the compiler will add it automatically
		System.out.println("Worker()");
	}
	public Worker(String name, int age, int salary) {
		super(name, age); // Represents a parameterized constructor that calls the parent class
		System.out.println("Worker(String, int, int)");
		//setName(name);
		//setAge(age);
		setSalary(salary);
	}
	
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		if(salary >= 2200) {
			this.salary = salary;
		} else {
			System.out.println("The salary is unreasonable!!!");
		}
	}
	
	// Custom member methods describe the behavior of the work
	public void work() {
		System.out.println("Today's bricks are a little hot...");
	}
	// The custom show method overrides the version inherited from the parent class
	@Override  // Annotation / annotation, used to explain that the following method is a rewrite of the parent method. If it does not constitute a rewrite, the compilation will report an error
	public void show() {
		super.show(); // Represents calling the show method of the parent class
		System.out.println("My salary is:" + getSalary());
	}
}
/*
    Programming and implementing the test of Worker class
 */
public class WorkerTest {
	
	public static void main(String[] args) {
		
		// 1. Use parameterless method to construct Worker type objects and print features
		Worker w1 = new Worker();
		// When the subclass overrides the show method, the following calls the later version
		w1.show(); // null  0
		
		System.out.println("----------------------------------");
		// 2. Construct Worker type objects with parameters and print features
		Worker w2 = new Worker("zhangfei", 30, 3000);
		w2.show(); // zhangfei ...
		// Call member method test
		w2.eat("Bean sprouts");
		w2.play("Glory of Kings");
		w2.work();
	}
}
Person()
Worker()
I am null,I'm 0 years old!
My salary is: 0
----------------------------------
Person(String, int)
Worker(String, int, int)
I am zhangfei,I'm 30 years old!
My salary is: 3000
 Bean sprouts are delicious!
King Rong Yao is so fun!
Today's bricks are a little hot...

Principle analysis of subclass object creation

Framework of inheritance relationship

Common tools for Java development

  • Text Editor (TE, Text Editor)
    • Notepad + +, Edit Plus, UltraEdit
  • Integrated Development Environment (IDE)
    • Jbuilder,NetBeans,Eclipse,MyEclipse,IDEA,...

Download and installation methods

  • Download address: https://www.jetbrains.com/
  • Installation method: click next to install by default

Case title

  • Program to realize the encapsulation of Animal class. The features include: name and coat color. It is required to provide a method to print all features.
  • Program to realize the encapsulation of Dog class and inherit from Animal class. The characteristics of this class include: the number of teeth. It is required to provide a method to print all characteristics.
  • The DogTest class is implemented by programming. In the main method, the Dog type objects are constructed by non parametric and parametric methods respectively, and the characteristics are printed
public class Animal {
    private String name;
    private String color;

    public Animal() {
    }
    public Animal(String name, String color) {
        setName(name);
        setColor(color);
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }

    public void show() {
        // South carriage return generates the printed statement
        System.out.println("name:" + getName() + ", Color:" + getColor());
    }
}
public class Dog extends Animal {
    private int tooth;

    public Dog() {
        super(); // Indicates that the parameterless constructor of the calling parent class is automatically saved
    }
    public Dog(String name, String color, int tooth) {
        super(name, color); // Represents a parameterized constructor that calls the parent class
        setTooth(tooth);
    }

    public int getTooth() {
        return tooth;
    }
    public void setTooth(int tooth) {
        if (tooth > 0) {
            this.tooth = tooth;
        } else {
            System.out.println("The number of teeth is unreasonable!!!");
        }
    }

    @Override
    public void show() {
        super.show();
        System.out.println("The number of teeth is:" + getTooth());
    }
}
public class DogTest {

    public static void main(String[] args) {
        // 1. Use parameterless method to construct Dog type objects and print features
        Dog d1 = new Dog();
        d1.show(); // null null 0

        // 2. Construct Dog type objects with parameters and print features
        Dog d2 = new Dog("Wangcai", "white", 10);
        d2.show(); // Wangcai white 10
    }
}
name: null, Color: null Number of teeth: 0 Name: Wangcai, Color: white number of teeth: 10

Tags: Java

Posted on Wed, 08 Sep 2021 03:14:56 -0400 by Jenling