1. The inheritance

1.1 Why class inheritance? (Inheritance benefits)

  1. The code redundancy is reduced and the code reusability is improved
  2. Facilitate the extension of functions
  3. It provides the premise for the use of polymorphism in the future

1.2 Inheritance in Java

  1. A class can be inherited by more than one subclass.
  2. Single inheritance of classes in Java: a class can have only one parent class
  3. Child and parent are relative concepts.
  4. The parent from which a subclass inherits directly is called the immediate parent. An indirectly inherited parent is called an indirect parent
  5. When a subclass inherits its parent, it gets the properties and methods declared in both the immediate parent and the indirect parent

1.3 Understanding of java.lang.Object class

  1. A class inherits from the java.lang.Object class if we do not explicitly declare its parent
  2. All Java classes (except java.lang.Object) inherit directly or indirectly from the java.lang.Object class
  3. This means that the Java class has the functionality declared by the java.lang.Object class.

1.4 practice

package oop.zhong;

public class ManKind {
	/** Define a ManKind class, Void manOrWoman() displays man(sex==1) or woman(sex==0) displays "No" Job "(salary==0) or" Job "(salary! = 0) * /
	private int sex;
	private int salary;
	
	
	
	
	public ManKind() {
		//super();
	}

	public ManKind(int sex, int salary) {
		//super();
		this.sex = sex;
		this.salary = salary;
	}

	public void manOrWoman(){
		if(sex == 1){
			System.out.println("man");
		}else if(sex == 0){
			System.out.println("woman");
		}
	}
	
	public void employeed(){
		if(salary == 0){
			System.out.println("no job");
		}else{
			System.out.println("job");
		}
	
	}

	public int getSex() {
		return sex;
	}

	public void setSex(int sex) {
		this.sex = sex;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary; }}Copy the code
package oop.zhong;

public class Kids extends ManKind{
/** * Define class Kids inheriting ManKind and include member variable int yearsOld method printAge() to print the value of yearsOld. * /
	
	private int yearsOld;

	
	
	
	
	public Kids() {
	//super();
	}

	public Kids(int yearsOld) {
	//super();
	this.yearsOld = yearsOld;
	}

	public int getYearsOld() {
		return yearsOld;
	}
	
	public void setYearsOld(int yearsOld) {
		this.yearsOld = yearsOld;
	}
	
	
	
	public void printAge(){
		System.out.println("I am " + yearsOld + " years old."); }}Copy the code
package oop.zhong;

public class KidsTest {
/** Define KidsTest, instantiate Kids' object someKid in main, and use this object to access member variables and methods of its parent class. * * /
	public static void main(String[] args) {
		Kids someKid = new Kids(12);
		
		someKid.printAge();
		someKid.setSalary(0);
		someKid.setSex(1); someKid.employeed(); someKid.manOrWoman(); }}Copy the code

2. Rewrite the

2.1 definition:

In subclasses, methods inherited from the parent class can be modified as needed, also known as method reset, overwriting. When the program executes, the methods of the subclass override the methods of the parent class.

2.2 requirements:

  1. The method overridden by a subclass must have the same method name and argument list as the method overridden by its parent class
  2. Subclass overrides the methodThe return value type cannot be greater than the parent classThe return value type of the method being overridden
    • If the parent overrides a method whose return type is void, the child overrides a method whose return type must be void
    • The return value type of the method overridden by the parent class is type A, then the return value type of the method overridden by the subclass can be class A or A subclass of class A
    • If the method overridden by its parent class returns a primitive data type (e.g., double), the method overridden by its subclass must return the same primitive data type (also double).
  3. Subclass overrides the access used by methodsThe permission cannot be smaller than the parent classAccess permissions for overridden methods
    • A subclass cannot override a method declared private in its parent class
  4. A subclass method must not throw an exception larger than that of the overridden method of its parent class

2.3 note:

Methods in subclasses that have the same name and arguments as those in their parent classes must be declared either non-static (that is, overridden) or static (not overridden). Because static methods belong to classes, subclasses cannot override methods of their parent class.

2.4 practice

/* Change the defined class Kids, redefine the employeed() method in Kids, * override the employeed() method defined in parent class ManKind * print "Kids should study and no job." * */
Copy the code

2.5 Distinguish method overrides and overloads?

  • Concepts of the two:

  • Specific rules for overloading and overwriting:

  • Form of expression:

    • Overloading: does not show polymorphism.
    • Rewrite: manifests as polymorphism.

Overloading means that multiple methods with the same name are allowed to exist with different parameters. The compiler modifies the name of a method with the same name based on its argument list. To the compiler, these methods with the same name become different methods. Their call addresses are bound at compile time.

Java overloading can include superclasses and subclasses, that is, subclasses can override methods with the same name and different parameters of the parent class. For overloading, the compiler determines the method to be called before the method is called. This is called “early binding” or “static binding” **;

With polymorphism, the explain runner does not determine the specific method to call until the moment the method is called, which is called “late binding” or “dynamic binding” **.

To quote Bruce Eckel: “Don’t be silly, if it’s not late bound, it’s not polymorphic.”

3. Permission modifiers

4. Super

Super can be used to call: properties, methods, constructors * * 3. Super can be used to call properties and methods * * 3.1 We can use methods or constructors in subclasses. An explicit call to a property or method declared in the * parent class by using "super. property "or "super. method". In general, however, we omit "super." * 3.2 Special case: when a property of the same name is defined in a subclass and a parent class, we must explicitly * use "super "in order to call the property declared in the parent class from the subclass. Property ", indicating that the property declared in the parent class is called. * 3.3 Special case: when a subclass overrides a method in its parent class and we want to call the overridden method in the subclass, we must explicitly * use "super ". Method ", indicating that a method in the parent class is being overridden. 4.1 We can explicitly use "super(parameter list)" in the constructor of a subclass. 4.2 The use of "super(parameter list)" must be declared in the first line of the subclass constructor! * 4.4 There is no explicit declaration of "this(parameter list)" or "super(parameter list)" in the first line of the constructor. By default, the constructor for the hollow parameter of the parent class is called: super() * 4.5 In at least one of the class's constructors, "super(parameter list)" is used in the constructor of the parent class */
Copy the code

5. The Instance inheritance

When a subclass inherits from its parent class, it obtains properties or methods declared in the parent class. * Subclass objects, in heap space, will be loaded with all the properties declared in the parent class. * * When we create a subclass object through the constructor of a subclass, we must directly or indirectly call the constructor of the parent class, and then call the constructor of the parent class... * until the constructor for the hollow parameter of the java.lang.Object class is called. Because all of the superclass structures are loaded, you can see that there are * superclass structures in memory, and subclass objects can be considered for calling. * * * Unambiguous: Although the parent class constructor is called when the subclass object is created, there is always one object created, which is a subclass of new. * * /
public class InstanceTest {}Copy the code

5.1Instance Inheritance and super exercises

/ / not posted
Copy the code

6. Polymorphism

package oop.polymorphism;
1. Understand polymorphism: It can be understood as many forms of the same thing. * Object polymorphism: a reference from a parent class refers to an object of a child class (or a reference from an object of a child class to a parent class) * * 3. Use of polymorphism: virtual method calls * With object polymorphism, we can only call methods declared in the parent class at compile time, but at run time we actually perform subclasses overriding the parent class's methods. * Summary: Compile, look left; Run, look to the right. * * 4. The use of polymorphism: ① class inheritance relationship ② method rewrite * * 5. Object polymorphism applies only to methods, not properties (see left for both compile and run) */
public class PersonTest {

	public static void main(String[] args) {
        Person p1 = new Person();
        p1.eat();

        Man man = new Man();
        man.eat();
        man.age = 25;
        man.earnMoney();
        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *");

        // Object polymorphism: a reference from a parent class refers to an object from a subclass
        Person p2 = new Man();

        // The use of polymorphism: when calling a method with the same name and arguments as its parent class, the subclass overrides the parent class's method - a virtual method call
        p2.eat();/ / Ctrl to the Person
        p2.walk();
        //p2.earnMoney(); / / an error.
        //earnMoney() is undefined for the type Person

        System.out.println(p2.id);/ / 1001
        //Person1001 Man1002}}Copy the code

For example, 6.1

package oop.polymorphism;

import java.sql.Connection;

public class AnimalTest {

	public void func(Animal animal){//Animal animal = new Dog();
		animal.eat();
		animal.shout();
		
// if(animal instanceof Dog){
// Dog d = (Dog)animal;
// d.watchDoor();
/ /}
	}
	
	public static void main(String[] args) {
		AnimalTest test = new AnimalTest();
		test.func(new Dog());
		// Dogs eat bones
		/ / wang! Wang! Wang!
		test.func(new Cat());
		/ / the cat eat the fish
		/ / meow! Meow!!! Meow!!!
	}
	
//	public void func(Dog dog){
//	dog.eat();
//	dog.shout();
/ /}
//public void func(Cat cat){
//	cat.eat();
//	cat.shout();
/ /}
}


class Animal{
	
	
	public void eat(){
		System.out.println("Animals: Feeding.");
	}
	
	public void shout(){
		System.out.println("Animal: Bark"); }}class Dog extends Animal{
	public void eat(){
		System.out.println("Dogs eat bones.");
	}
	
	public void shout(){
		System.out.println("Woof! Wang! Woof!");
	}
	
	public void watchDoor(){
		System.out.println("Door"); }}class Cat extends Animal{
	public void eat(){
		System.out.println("Cats eat fish.");
	}
	
	public void shout(){
		System.out.println("Meow! Meow!!! Meow!"); }}// Example 2:

class Order{
	
	public void method(Object obj){
		// As long as Object, can inherit overwrite, can be polymorphic}}// Example 3:
class Driver{
	
	public void doData(Connection conn){
		// conn = new MySQlConnection(); / conn = new OracleConnection();
		// Normative steps to manipulate data
// conn.method1();
// conn.method2();
// conn.method3();
		//MySQlConnection or OracleConnection method can be overridden and called directly from here}}Copy the code

6.2 Inapplicability of polymorphism

// Object polymorphism applies only to methods, not properties (see left for compilation and execution)
// Object polymorphism: a reference from a parent class refers to an object from a subclass
Person p2 = new Man();

System.out.println(p2.id);/ / 1001
//Person1001 Man1002
Copy the code

6.3 Virtual method Invocation

package oop.polymorphism1;

import java.util.Random;

// Interview question: is polymorphism a compile-time behavior or a runtime behavior? run
// The proof is as follows:
class Animal  {

	protected void eat() {
		System.out.println("animal eat food"); }}class Cat  extends Animal  {

	protected void eat() {
		System.out.println("cat eat fish"); }}class Dog  extends Animal  {

	public void eat() {
		System.out.println("Dog eat bone"); }}class Sheep  extends Animal  {


	public void eat() {
		System.out.println("Sheep eat grass");

	}


}

public class InterviewTest {

	public static Animal  getInstance(int key) {
		switch (key) {
		case 0:
			return new Cat ();
		case 1:
			return new Dog ();
		default:
			return new Sheep ();
		}

	}

	public static void main(String[] args) {
		int key = new Random().nextInt(3); System.out.println(key); Animal animal = getInstance(key); animal.eat(); }}Copy the code