11, Object oriented inheritance, abstraction and method rewriting“

Posted by Infinitive on Thu, 27 Jan 2022 14:05:28 +0100

1. Inherit

1.1. Inheritance and introduction

The three classes have duplicate code. You can extract the common code and put it into another class; The following three classes need to have some relationship (inheritance) with the above class. The above class is called parent class (superclass, base class and root class), and the following class is called subclass (derived class and extended class);

Benefits: improved code reusability

1.2. Inheritance function:

Code reuse to improve development efficiency and program scalability.

1.3 basic syntax of class inheritance in Java

① Syntax format of inheritance in Java class:

class A{}

class B extends A{}

A is the parent class, base class, root class and superclass of B

B is the subclass, derived class and extended class of A

② Verify: whether the subclass can inherit things from the parent class (operate things inherited from the parent class by creating subclass objects)

1.4. Case code:

Parent class:

public class Animal {
	String name;
	int age;
	public void eat() {
		System.out.println("eat");
	}
}

Subclass:

public class Person extends Animal{
	/**
	 * Human unique method
	 */
	public void coding() {
		System.out.println("Knock code...");
	}
}

public class Pig extends Animal{
	/**
	 * Unique method for pigs
	 */
	public void gongBaiCai() {
		System.out.println("Arch cabbage...");
	}
}

public class Bird extends Animal{
	/**
	 * Unique method of birds
	 */
	public void fly() {
		System.out.println("fly...");
	}
}

Test class:

/**
 *	Inheritance test class
 */
public class AnimalTest {

	public static void main(String[] args) {
		//Create subclass object
		Person person = new Person();
		
		Pig pig = new Pig();
		
		//Call the members inherited from the parent class through the subclass object
		person.age = 1;
		person.eat();
		System.out.println(person.name);
		System.out.println(person.age);
		//Call subclass specific methods
		person.coding();
		
		pig.name = "Page";
		pig.age = 7;
		pig.eat();
		System.out.println(pig.name);
		System.out.println(pig.age);
		//Call subclass specific methods
		pig.gongBaiCai();
	}
}

2.4} which members can a subclass inherit from its parent class?

Except that construction methods cannot be inherited, others can be inherited

However, privatized members cannot be accessed directly through subclass objects, but can be accessed indirectly through inherited public methods.

The code is as follows:

Parent class:

public class Animal {
	String str;
	private int a;
	static int b;
	public Animal() {
		System.out.println("Nonparametric structure...");
	}
	public Animal(int a) {
		System.out.println("Parametric structure...");
	}
	public void test() {
		System.out.println("Common method");
	}
	public static void testStatic() {
		System.out.println("Static method..");
	}	
	private void testPrivate() {
		System.out.println("Privatization method..");
	}
	public int getA() {
		return a;
	}
	public void setA(int a) {
		this.a = a;
	}
}

Subclass:

public class Person extends Animal{
	/**
	 * Human unique method
	 */
	public void coding() {
		System.out.println("Knock code...");
	}
}

Test code:

/**
 *	Test which members to inherit
 */
public class AnimalTest {

	public static void main(String[] args) {
		//Create subclass object
		Person person = new Person();
		
		//Call the normal member variable inherited from the parent class through the subclass object
		person.str = "Zhang San";
		
		//Call the private member variable inherited from the parent class through the subclass object
//		person.a = 1; // A parent class privatized member cannot be called directly through a subclass object
		
		//Call the static member variable inherited from the parent class through the subclass object
//		person.b = 2; // Don't use it like that. When compiling here, the person object will be directly compiled into the class name
		
		//Call the normal method inherited from the parent class through the subclass object
		person.test();
		
		//Call the static method inherited from the parent class through the subclass object
//		person.testStatic(); // Don't use it like that. When compiling here, the person object will be directly compiled into the class name
		
		//Call the privatization method inherited from the parent class through the subclass object
//		person.testPrivate(); // Privatization methods cannot be called directly
		
		//Subclass calls can indirectly call the privatized members in the parent class through the public methods of the parent class
		person.setA(69);
		
		int a = person.getA();
		System.out.println(a);//69
		
		//Call the method inherited from Object
		int hashCode = person.hashCode();
		System.out.println(hashCode);
	}

}

2.5 inheritance characteristics of classes in Java

① Single inheritance (a class can only have one direct parent)

② Multiple inheritance (multi-level inheritance), a class can have subclasses, subclasses can also subclasses  

Example:

class A{}

class B extends A{}

class C extends B{}

class D extends C{}

③ Each class has a direct parent class. If you don't see the inheritance code displayed, you will implicitly inherit Object

2. Method Override (Override / Override)

2.1 method override

2.1.1 introduction of method override (why override method is needed)

Overload: same type, same name, different parameters

 

2.1.2 method override function:

Ensure business logic rationality

2.1.3 method override syntax:

Directly copy the method to be overridden in the parent class to the child class, and then override the method body

  1.         1. Rewriting can only occur in inheritance relationships. When a class inherits its parent method, it has the opportunity to override the parent method. The premise is that the method of the parent class is not modified by final.
    1.         2. The method signatures (method name + parameter list) of subclass methods and parent methods are exactly the same.
      1.         3. Access permission: the access permission of the subclass method is greater than or equal to that of the parent method.
        1.         4.static/private methods cannot be overridden (java syntax).
          1.         5. Return value type: the return value type of the subclass method can be a subclass of the return value type of the parent method or equal.
            1.         6. The Exception thrown by the subclass is the Exception or equivalent thrown by the corresponding method of the parent class.
            2. Example code:

              // Parent class
              public class Animal {
              	public void eat() {
              		System.out.println("eat");
              	}
              }
              
              // inherit
              public class Person extends Animal{
              	@Override//Annotation, compile time, check code
              	public void eat() {
              		System.out.println("Eat pigs");
              	}
              }
              // inherit
              public class Pig extends Animal{
              	public void eat() {
              		System.out.println("Eat cabbage....");
              	}
              }

              Test code:

              /**
               *	Method override test class
               */
              public class AnimalTest {
              	public static void main(String[] args) {
              		//Create subclass object
              		Person person = new Person();
              		Pig pig = new Pig();	
              		person.eat();//Method after subclass override
              		pig.eat();//Method after subclass override
              	}
              }

              2.1.4 precautions for method override:

              1. Not every inherited method needs to be rewritten.

              2. Not every subclass should override the methods inherited from the parent class.

              2.2.super keyword

              The problem is that when a method in a subclass needs to call the overridden method in the parent class, the super keyword must be used.

            3. public class Ostrich extends Bird{ 
                  public void fly() { 
                      System.out.println("Flapping wings,Run fast..."); 
                  }
              
                  public void say() { 
                      super.fly(); //Call the method whose parent class is overridden 
                      fly(); //Call methods in this class 
                  } 
              }

              If the overridden method is called without using the super keyword, the method in this class is called.

              super keyword indicates the meaning of the parent object.

              super.fly() can be translated into a fly method that calls the parent object.

              3. Abstract classes and abstract methods

              3.1 introduction of abstract methods

            4. /**
              *	Graphic classes (abstract classes) can only be abstract classes that hold abstract methods
               */
              public abstract class AbstractGraph {
              	/**
              	 * Method of obtaining area: since the method of obtaining area is different for each subclass of graphic class, in order to ensure the rationality of business,
                       * Each subclass must be forced to rewrite the method, which is realized through the syntax structure of abstract method.
              	 * @return
              	 */
              	public abstract double getArea();
              }

              Abstract method: a method without method body and modified with abstract

              Syntax: modifier abstract return value type method name (...);

              Function of abstract method: in order to ensure the rationality of business logic, force subclasses to rewrite methods according to their own needs.

            5.  

              3.2 abstract class

              Abstract class: a class decorated with abstract.

              Abstract class function: it is used to hold abstract methods.

              Syntax: name the general class AbstractXxx

            6. Modifier abstract class AbstractXxx{

              Instance variable

              Class variable

              Example method

              Class method

              Constructor / / syntax: an abstract class cannot create an object. Can only be used in subclasses through super

              abstract method: the modifier abstract returns the value type method name (...);

              }

              Usage scenario of abstract class: it is generally used as a business parent class (base class, template class), and some methods in the business parent class need to be overridden by all subclasses.

              For example, the template method pattern.

            7. Supplement the above graphic subclass Code:

              /**
               *	circular
               */
              public class Circle extends AbstractGraph {
              private double r;
              
              public Circle() {}
              	
                  public Circle(double r) {
              	this.r = r;
              }
              	
              public double getR() {
              return r;
              }
              
              public void setR(double r) {
              this.r = r;
              }
              
              @Override
              public double getArea() {
              	return Math.PI * r * r;
              }
              }
              
              /**
               *	rectangle
               */
              public class Ractangle extends AbstractGraph {
              private double height;
                  private double width;
              	
                  public Ractangle() {}
              
              public Ractangle(double height, double width) {
              	super();
              	this.height = height;
              	this.width = width;
              }
              
              public double getHeight() {
              	return height;
              }
              
              public void setHeight(double height) {
              	this.height = height;
              }
              
              public double getWidth() {
              	return width;
              }
              
              public void setWidth(double width) {
              	this.width = width;
              }
              
              @Override
              public double getArea() {
              	return height * width;
              }
              }

              Test code:

              /**
               *	Abstract class test exercise
               */
              public class GraphTest {
              
              public static void main(String[] args) {
              	// Create subclass object
              	Circle circle = new Circle(5);	
              	Ractangle ractangle = new Ractangle(3,5);
              		
              	// Call the method inherited from the parent class
              	double circleArea = circle.getArea();
              	double ractangleArea = ractangle.getArea();
              		
              	System.out.println("Circular area:"+circleArea);
              	System.out.println("Rectangular area:"+ractangleArea);
              		
              //	new AbstractGraph();// Abstract classes cannot create objects
              }
              }

              4. Object class (and application of method override)

              4.1} Object class import

              Class Object , is the root class of the class hierarchy. Each class uses Object , as a superclass.

              All objects (including arrays) can call methods in the Object;

              4.2 methods in object class

              1. int # hashCode() returns the hash code value of the object.

              2. boolean equals(Object obj) determines whether the values of two object member variables are "equal" according to the actual business, not directly==

              Judge whether the addresses of the current object and obj parameters are "equal". To compare what type of object, override the equals method of its corresponding type.

              For example:

              For two students, we think that the member variable: the same name and phone number is the same person, so we use the equals method of rewriting the student class.

              Two teachers, we think that the membership variable is the same ID number, which is the same person, using the equals method of rewriting the teacher class.

              3. String toString() returns the string representation of the object. If you need to print the format of the object, you need to override the toString method of the class corresponding to the current object.

              4. Class getClass() returns the runtime class of this Object, that is, the bytecode file corresponding to the current Object.   

              (focus on reflection) bytecode files are compared with = =

              4.3. toString method

              Direct print object: the result is the address

            8.  

              Why? Get the calling relationship in the figure below through code tracking

              The code trace is as follows:

            9. Therefore, as long as the toString method of the User class is rewritten, only the format can be printed

              Example code:
              /**
                * Requirement: if you want to print the object in the specified format: [Lao Wang next door, 9969] [value of name, value of phoneNumber], you need to override the toSting method of the current Student class
                */
              @Override
              public String toString() {
                  return "[" + name + "," + phoneNumber + "]";
              }

              4.4,equals

              There are the following requirements: for two students, we think that the member variables: the same name and phone number are the same person, so we use the equals method of rewriting the student class.

              The result of equals comparison is: false. Why? Because the equals method is not overridden, it inherits the equals method in the Object by default, = = compare

Therefore, the equals method must be rewritten according to the actual needs:

/**
* Because polymorphism has not been learned here, write the formal parameter Object as Student, and then delete @ Override
  * 
* Comparing reference types is generally compared with equals== Is the address of the comparison
  * Here, we only need to compare the values in the String object
  * this.name Is a String type. Compare the values of String type with the equals method of String
*/
// public boolean equals(Object obj) {because polymorphism has not been learned here, write the formal parameter Object as Student, and then delete @ Override
public boolean equals(Student stu) {
    //Requirement: for two students, we think that the same name and phone number are the same person, so we use the equals method of rewriting the student class
    //To compare the values of two reference types, use the equals method of the reference type, here this Name is the equals method of String. And the equals method of String has been overridden
    if (this.name.equals(stu.name) && this.phoneNumber.equals(stu.phoneNumber)) {
    	return true;
    }
    return false;
}

The complete code after rewriting the method is as follows:

/**
 *   Student class
 */
public class Student {
private String name;
private String phoneNumber;
    int age;
public Student() {}
	
public Student(String name, String phoneNumber) {
	this.name = name;
	this.phoneNumber = phoneNumber;
}
	
public String getName() {
	return name;
}
	
public void setName(String name) {
	this.name = name;
}
	
public String getPhoneNumber() {
	return phoneNumber;
}
	
public void setPhoneNumber(String phoneNumber) {
	this.phoneNumber = phoneNumber;
}
	
/**
 * Requirement: if you want to print the object in the specified format: [Lao Wang next door, 9969] [value of name, value of phoneNumber], you need to override the toSting method of the current Student class
 */
@Override
public String toString() {
	return "[" + name + "," + phoneNumber + "]";
}
	
/**
 * Because polymorphism has not been learned here, write the formal parameter Object as Student, and then delete @ Override
 * 
 * Comparing reference types is generally compared with equals== Is the address of the comparison
 * Here, we only need to compare the values in the String object
 * this.name Is a String type. Compare the values of String type with the equals method of String
 */
//  public boolean equals(Object obj) {because polymorphism has not been learned here, write the formal parameter Object as Student, and then delete @ Override
public boolean equals(Student stu) {
	// Requirement: for two students, we think that the same name and phone number are the same person, so we use the equals method of rewriting the student class
	// To compare the values of two reference types, use the equals method of the reference type, here this Name is the equals method of String. And the equals method of String has been overridden
	if (this.name.equals(stu.name) && this.phoneNumber.equals(stu.phoneNumber)) {
	    return true;
	}
	return false;
} 
}

Test code:

public class StudentTest {

public static void main(String[] args) {
	Student stu1 = new Student("Lao Wang next door","9969");
		
	Student stu2 = new Student("Lao Wang next door","9969");
		
	// 1. Call the hashCode method inherited from Object
	System.out.println("stu1 Hash value of:"+stu1.hashCode()); // 366712642
	System.out.println("stu2 Hash value of:"+stu2.hashCode()); // 1829164700
		
	// 2. The printing object is the address: characteristics (hexadecimal of hash code of fully qualified package name + @ + object)
	// Requirement: if you want to print the object in the specified format: [Lao Wang next door, 9969] [value of name, value of phoneNumber], you need to override the toSting method of the current Student class
	System.out.println(stu1); // cn.xianshu.object.Student@15db9742
	System.out.println(stu2); // cn.xianshu.object.Student@6d06d69c
		
	// 3. boolean equals(Object obj) determines whether two objects are "equal" according to the actual business, not directly==
	// Requirements: for two students, we think that the member variable: the same name and phone number is the same person, so we use the equals method of rewriting the student class
	System.out.println(stu1.equals(stu2)); //Judge whether stu1 object is equal to stu2 object. true if equal, false otherwise
		
	// 4. Class getClass() returns the runtime class of this Object, that is, the bytecode file corresponding to the current Object (the most commonly used reflection). The bytecode file is compared with = =
	Class<? extends Student> clazz = stu1.getClass();
	System.out.println(clazz); // class cn.xianshu.object.Student
		
	Class<? extends Student> clazz2 = stu2.getClass();
	System.out.println(clazz2); // class cn.xianshu.object.Student
		
	// Whether byte code files are equal or not is judged by = =
	System.out.println(clazz == clazz2); // true
		
}

}

4.5 = = difference from equals (interview question)

1.== :  

Compare basic data types: compare whether the values are equal.

Compare reference data types: compare whether the addresses of objects are equal.

2. equals can only be used for reference types

Compare whether the two objects are equal according to the actual business. The default is not to override = = comparison. In actual development, we generally compare objects through their attribute values (generally, the address of the comparison Object is not very useful), so we will override this method in the Object and write our own judgment mechanism in the method;

Next chapter 12, "object oriented interface and polymorphism" 4

Topics: Java Back-end OOP