day11 object-oriented programming

1. Inheritance

Subclass Object Creation Process

Principle: First father, then son

1) Check in the Method Zone whether templates for all classes in the inheritance system of the class to which the object to be created have been loaded

2) If not loaded, all class templates are loaded by the class loader in order from parent to child

3) If all class templates have been loaded, they will not be loaded and only one class template will be guaranteed

4) Open up space in the GC area based on the definition information of attributes in all classes, attribute ordering must be from parent to child

5) JVM writes all this space to 0

6) Perform explicit assignment of parent attributes

7) Execute parent constructor

8) Perform display assignment of subclass attributes

9) Execute Subclass Constructor

10) Return object header address

this is the caller object (who calls who)

Memory Diagram 

2. Polymorphism

What is the difference between native and polymorphic?

Polymorphism: The multiple parent forms of subclass objects, that is, the use of subclass objects as parent objects

                eg: Xiao Ming is a human;Xiaoming is an animal, Xiaoming is a creature

Native state: the subclass form of a subclass object

Native Reference: The address of a subclass object is assigned to a reference object of a subclass type

Polymorphic reference: The address of a subclass object is assigned to a reference object of the parent type, which essentially treats the subclass object as a parent object

Use, just switch perspective, object body never changes

What are polymorphic side effects?

Polymorphic side effects: When polymorphic references occur, subclass-specific members are inaccessible

What are the two aspects of polymorphism?

1) From right to left: multiple paternal forms of subclass objects

2) From left to right: reference variables of parent type point to multiple different subclass objects

The type on the left is called the compile-time type, and the type on the right is called the runtime type

Under what circumstances do polymorphisms occur?

Polymorphism occurs when compile-time and run-time types are different

What you can adjust is determined by the type on the left (compile-time type) and the runtime type on the right

References to subclass objects directly invoke methods to execute subclass

Prerequisites for polymorphism:

1) Inheritance or implementation relationship is required

2) Method Override

When do I use this state?

Native, other all-purpose polymorphisms when subclass-specific members must be used frequently

Virtual Method Calls (Important)

Definition: A polymorphic reference calls an override method, which is a virtual method call

The execution of a method always looks at what the new er does, executing subclass methods

Why is it called a virtual method call?

1) To check the parent type at compile time, the only function of the method in the parent deceives the compiler and does not execute at all, but it cannot be deleted

2) Runtime Execution Subclass Type (Runtime Type), Dynamic Binding

 public static void main1(String[] args) {
        /**
         * Native Reference
         */
//        Chinese ch = new Chinese();
//        System.out.println(ch.toString());
//        ch.sayHello();References to subclass objects directly invoke methods to execute subclass
        /**
         * A polymorphic reference, in which a subclass object is assigned to a reference variable of the parent type, is essentially a use of subclass objects as yes and as parent objects
         * Just switching perspective, the object's body never changes
         */
        Person p1 = new Chinese();
        System.out.println(p1.getName());
        p1.sayHello();//Polymorphic Reference Call Override Method
        /**
         * Polymorphic reference calls to override methods, also known as virtual method calls, that execute methods in subclasses
         * 1)Check parent type (compile-time type) at compile time
         * 2)Runtime Execution Subclass Type (Runtime Type), Dynamic Binding
         */

        p1 = new American("Jack", 34, "male", true);
       // p1.spring();
        //p1.shoot();

        /**
         * Subclass-specific members are inaccessible when polymorphic references occur
         * This is a side effect of polymorphism because p1 is pointing to ambiguity
         *  p1 Objects of type Person, things of type Person don't have this behavior, so they can't be accessed
         */

        p1.sayHello();
    }

What is the inherent logic of virtual methods?

This behavior should be present in the parent type, but how to override it is unknown to the child class

Note:

Methods in subclasses can override methods in parent classes. Methods can be overloaded, so they are polymorphic and depend on the type

Attributes in a subclass and attributes in a parent coexist, so there is no polymorphism in attributes, just the type is enough

package com.atguigu.javase.test;
/**
 * Methods in subclasses can override methods in the parent, so methods are polymorphic
 * Attributes in subclasses and attributes in parent classes coexist without polymorphism
 */
class Base{
    int count = 10;
    public void display(){
        System.out.println(this.count);//10
    }
}
class Sub extends Base{
    int count = 20;
    public void display(){
        System.out.println(this.count);//20
    }
            
}
public class FieldMethodTest {
    public static void main(String[] args) {
        Sub s = new Sub();
        System.out.println(s.count);//Attributes of the type 20 s belongs to
        s.display();//20 subclass methods
        Base b = s;//Polymorphic Reference
        System.out.println(b == s);//true Compares the data value in two variables with two references==and the address value in the comparison
        System.out.println(b.count);//Attribute 10 does not have polymorphism
        b.display();//Method 20 has polymorphisms and implements methods in subclasses
    }
   
}


Applications of Polymorphism

1) Polymorphic array, good compatibility

Any object of this class or subclass can be saved in it

Different objects can be unified for batch processing

public static void main2(String[] args) {
        //Polymorphic array in which any class or subclass object can be saved
        Person[] arr = new Person[5];
        //Store different subclass objects in a parent array
        arr[0] = new Chinese("Li Si",40,"male","green");
        arr[1] = new Chinese("Lili",25,"female","red");
        arr[2] = new American("Rose",45,"female",false);
        arr[3] = new American("lue",15,"female",true);
        arr[4] = new Person("Mingming",13,"male");
        //Sort by price
        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;//Record Minimum Subscript ii
            for (int j = minIndex + 1; j < arr.length - 1; j++) {
                if(arr[j].getAge() < arr[minIndex].getAge()){
                    minIndex = j;
                }
            }
            Person tmp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = tmp;
        }
        //Traversing Print Output
        for (Person p : arr) {
            System.out.println(p.toString());
        }

Polymorphic sorting, select common properties

2) Polymorphic parameter methods

Advantage: Compatible with all objects of this class and subclass

Disadvantage: Fuzzy and indeterminate type

Format: chinese ch = (Chinese)p

instanceof operator: determines whether the object entity pointed to by the reference on the left is an entity of the right type

Format: x instanceof A

The essence of styling is role transition

It must be judged before modeling, and the type of object must be judged from the subclass to the parent class.

Styling is risky and must be judged first

/**
     * The polymorphic parameter method is compatible with all objects of this class and subclass, but with type of fuzzy uncertainty
     * Possibly objects of type Person and its subclasses
     */

    public static void test(Person p){
       p.sayHello();//Since it is not clear what this is, it is possible to make virtual method calls
        //p.spring;//Polymorphic side effects
        /**
         * Styling is risky, so judge first
         * Object type must be judged from the most subclass to the parent class
         */
        if(p instanceof Peking){
            ((Peking)p).playBird();
        }else if(p instanceof Chinese){
            ((Chinese)p).sayHello();
        }else if( p instanceof  American){
            ((American)p).sayHello();
        }else {
            System.out.println("I am an ordinary person");
        }
    }

Note: Parent object is not a subclass object, and subclass object is a parent object

3. Object Class

All Java root parent classes, classes without extends inherit Object by default

Purpose: For polymorphism, compatibility

Features: Only methods, no attributes

equals() method

Used to determine the contents of two objects

Is the content of this object equal to that of obj object, content is property

1) Object comparison must use equals method, never ==

2) The equals method is used to determine if the contents of the current this object and the objects in the parameters are equal

3)public boolean eauals(Object obj){

         Compare the content of this object with that of obj, content is property 

}

        The equals() in the parent Object is not good, is not better than the address, must be overridden in the child class to complete the comparison of content

        This method must be rewritten to complete the intended function!!!

4) The equals method is symmetric 

        If a.equals(b) is true, then b.equals(a) must also be true;

        If a.equals(b) is false, then b.equals(a) must also be false;

hashCode() method

Role: Gets the Hash code of the current object

Also known as hash codes, objects are hashed in memory

If the equals of two objects are true and the contents of the two objects are equal, the hash codes of the two objects must be equal to express the characteristic.

If the equals of two objects are true and the contents of the two objects are equal, the hash codes of the two objects must be not equal to express hash

The result of equals must be true, just like the hash code of two objects

Two objects are different, equals must result in false

Signature: Related to a feature, calculated from the object's own content

eg:MD5 code

 @Override
    public boolean equals(Object obj) {
        //Compare this object with obj object content
        if (obj instanceof Point){//Styling is risky, so you must first determine whether the reference on the left points to an object entity, which is of the right type.
            Point p2 = (Point)obj;//Style, convert it to
            /**
             * Where the name of this variable points to a memory space that retains the basic data type, the comparison is the value, that is, the content;
             * If the reference data type is compared, the address value
             */
            if (this.x == p2.x && this.y == p2.y){
                return true;
            }
        }
        return false;
    }
    @Override
    public int hashCode(){//Override hashCode method in subclass
        //As long as all the attributes are involved in the operation, it must be characteristic so that it can be hashed if it changes again
        return Integer.parseInt(x*10+""+y*10);
    }
}

Shortcut key generation equals() and hashcode() methods

toString() method

The special thing is that it is called automatically

1) When printing

2) When stitching strings

Make the object a string for printing convenience

    /** This is a toString in the parent class. It does not express the details of the object and must be overridden
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }*/

    @Override
    public String toString() {
        return "x : " + x + ", y : " + y;
    }

However, the toString() method must be overridden in a subclass

Do not call toString() again when printing object information

summary

What I'm learning today:

1) The process of creating inherited objects;

2) Polymorphism;

3) Three methods in the Object class;

Keywords: Java intellij-idea

Added by Ghostgator on Fri, 03 Sep 2021 19:26:42 +0300