[Han Shunping] Java OOP learning notes

Posted by Haberdasher on Thu, 27 Jan 2022 21:28:59 +0100

object-oriented programming

Java online course: Han Shunping learned Java from zero foundation in 30 days

1. Packaging

Implementation steps of encapsulation

  1. Privatize attributes [cannot modify attributes directly]
  2. A public set method is provided to judge and assign values to attributes
public void setXxx(/*Type parameter name*/){ // Xxx indicates an attribute
        // Add business logic for data validation
        // Attribute = parameter name;
}
  1. Provide a public get method to get the value of the property
public XX getXxx(){ // Authority judgment
        return xx;
}

2. Succession

1. Basic considerations for inheritance

  1. Subclasses inherit all properties and methods. Non private properties and methods can be accessed directly, but private properties and methods cannot be accessed directly in subclasses. They should be accessed through public methods
  2. The subclass must call the constructor of the parent class to complete the initialization of the parent class
  3. When creating a subclass object, no matter which constructor of the subclass is used, it will always call the parameterless constructor of the parent class by default. If the parent class does not provide a parameterless File Builder: you must use super in the constructor of the subclass to specify which constructor of the parent class is used to complete the initialization of the parent class. Otherwise, the compilation will not pass
  4. If you want to specify to call a constructor of the parent class, call it explicitly: super (parameter list)
  5. When using super, it needs to be placed in the first line of the constructor
  6. super() and this() can only be placed in the first line of the constructor, so the two methods cannot share a constructor (this() and super() are used in the constructor in the class, this() is another constructor calling the class itself, super() is the constructor calling the parent class, and this can be shared with super() if it is not used as the constructor)
  7. All classes in java are subclasses of the Object class, and Object is the base class of all classes
  8. The call of the parent constructor is not limited to the direct parent class! It will be traced up to the Object class (top-level parent class)
  9. A subclass can inherit at most one parent class (direct inheritance), that is, the single inheritance mechanism in java. Thinking: how can class a inherit classes B and C? [a inherits B, B inherits C]
  10. Inheritance cannot be abused. The logical relationship between subclass and parent class must meet is-a
Person is a Music?
Person Music
Music extends Person //unreasonable 
Anima
Cat extents Animal //reasonable

2. this and super

No.differencethissuper
1Access propertiesAccess the attribute in this class. If this class does not have this attribute, continue to find it from the parent classAccessing properties in the parent class
2Call methodAccess the method in this class. If this class does not have this method, continue to find it from the parent classDirect access to methods in the parent class
3Call constructor (one out of two)Calling this class constructor must be placed on the first line of the constructorWhen calling the parent class constructor, it must be placed in the first line of the child class constructor
4specialRepresents the current objectAccessing parent objects in subclasses

3. Method rewrite (method override)

  1. The parameter and method name of the method of the subclass should be exactly the same as the parameter and method name of the method of the parent class.
  2. The return type of the subclass method is the same as that of the parent method, or it is a subclass of the parent return type
  3. Access permission of subclass method ≥ access permission of parent method

4. Method rewriting and overloading

nameOccurrence rangeMethod nameparameter listReturn typeModifier
OverloadThis categoryMust be the sameThere is at least one difference in type, number and orderNo requirementNo requirement
OverrideParent child classMust be the sameMust be the sameThe return type of the subclass override method is consistent with that of the parent method, or it is a subclass of the return type of the parent methodAccess modifier of subclass method ≥ access modifier of parent class

3. Polymorphism

1. Basic concepts

  1. Polymorphism of methods -- polymorphism of method overloading + polymorphism of method rewriting

  2. Polymorphism of objects (core, difficulty, focus)
    Some important words of Lao Han (remember):

    1. The compile type and run type of an object can be inconsistent

    2. The compilation type is determined when defining the object and cannot be changed

    3. The operation type can be changed

    4. The compilation type is to the left of the = sign when defining, and the running type is to the right of the = sign

      Case:
      Animal animal= new Dog(); [the compilation type of animal is animal, and the operation type is dog]
      animal= new Cat(); [the running type of Animal is changed to cat, and the compilation type is still Animal]

2. Polymorphic upward transformation

The parent class reference points to the subclass object essence: the parent class reference points to the subclass object
Syntax: parent type reference name = new subclass type ();
Features: the compilation type is on the left, and the operation type is on the right
All members in the parent class can be called (subject to access permission)
Special members in subclasses cannot be called, because which members can be called in the compilation stage is determined by the compilation type
The final running effect depends on the specific implementation of subclasses!

3. Polymorphic downward transformation

Syntax: subclass type reference name = (subclass type) parent class reference;
Only references of the parent class can be coerced, and objects of the parent class cannot be coerced
It is required that the reference of the parent class must point to the object of the current target type, that is, the parent class reference originally points to the object of the subclass type to be forced
After the downward transformation, all members in the subclass type can be called

The compilation type determines the range that can be called, and the running type determines the final execution effect of the method

The attribute is not rewritten. The value of the attribute depends directly on the compilation type

instanceOf comparison operator, which is used to judge whether the operation type of the object is X type or a subtype of XX type

4. Dynamic binding mechanism of Java

1. When calling an object method, the method will be bound to the memory address / running type of the object
2. When calling object attributes, there is no dynamic binding mechanism. Where to declare and where to use

Tip: when you see the inheritance relationship, you should associate it with the problem of dynamic binding

5. Application of polymorphism

1. Polymorphic array

The definition type of the array is the parent type, and the actual element type saved in it is the subclass type

public class PolyArray {
    public static void main(String[] args) {
		//Teacher and Student are subclasses of Person
        Person[] people = new Person[5];
        people[0] = new Person("wjh", 16);
        people[1] = new Student("wjh", 17, 646);
        people[2] = new Student("xdd", 17, 630);
        people[3] = new Teacher("jls", 47, 8000);
        people[4] = new Teacher("yyg", 36, 7000);
        for (int i = 0; i < people.length; i++) {
            //people[i] the compilation type is Person, and the running type is determined by the JVM according to the actual situation
            System.out.println(people[i].say());//Dynamic binding

            //Type judgment + downward transformation, so that you can call methods unique to subclasses
            if (people[i] instanceof Teacher) {
                ((Teacher) people[i]).teach();
            } else if (people[i] instanceof Student) {
                ((Student) people[i]).study();
            } else if (people[i] instanceof Person) {

            } else {
                System.out.println("Your type is wrong, please check it yourself...");
            }
        }
    }
}

2. Polymorphic parameters

public class PolyParameter {
    public static void main(String[] args) {
        Worker tom = new Worker("Tom", 2500);
        Manager milan = new Manager("milan", 5000, 200000);
        PolyParameter polyParameter = new PolyParameter();
        polyParameter.showEmpAnnual(tom);
        polyParameter.showEmpAnnual(milan);

        polyParameter.testWork(tom);
        polyParameter.testWork(milan);
    }

    public void showEmpAnnual(Employee e) {
        System.out.println(e.getAnnual());  //Dynamic binding mechanism
    }

    //Polymorphic parameters
    public void testWork(Employee e) {
        if (e instanceof Worker) {	//Type judgment
            ((Worker) e).work();	//Downward transformation
        } else if (e instanceof Manager) {
            ((Manager) e).manager();
        } else {
            System.out.println("No treatment");
        }
    }
}

4. Detailed explanation of object class

1. Difference between = = and equals()

==Is a comparison operator
  1. ==: you can judge both basic types and reference types

  2. ==: if the basic type is judged, the judgment is whether the values are equal

    Example: int i=19; double d=10.0;

  3. If you judge the reference type, you judge whether the addresses are equal. That is to determine whether it is the same object

equals()
  1. equals: it is a method in the Object class and can only judge the reference type
  2. The default judgment is whether the addresses are equal. This method is often overridden in subclasses to judge whether the contents are equal

2. hashCode()

  1. Improve the efficiency of containers with hash structure!
  2. If two references point to the same object, the hash value must be the same!
  3. If two references point to different objects, the hash value is different
  4. The hash value is mainly based on the address number! Hash values cannot be fully equivalent to addresses
  5. Later in the set, the hash Code will also be rewritten if necessary

The hashCode method defined by the class Object does return different integers for different objects. This is usually achieved by converting the internal address of the Object to an integer, but the Java programming language does not need this implementation technology.

Tip: the internal address of the object is the actual address. Since Java runs on the virtual machine, we can't get the internal address of the object. In contrast, C/C + + can get the actual address

3. toString()

  1. Default return: full class name + @ + Hex of hash value [full class name is package name + class name]

  2. Subclasses often override toString() to return the property information of the object

  3. Rewrite toString(), and when printing objects and splicing objects, the toString form of the object will be automatically called [idea shortcut: alt + insert]

  4. When outputting an object directly, toString() is called by default

    System.out.println(monster) <=> System.out.println(monster.toString)

4. finalize()

  1. When an object is recycled, the system automatically calls finalize() of the object. Subclasses can override this method to release resources;
  2. When to recycle: when an object does not have any references, the jvm considers the object as a garbage object and will use the garbage collection mechanism to destroy the object. Before destroying the object, it will call finalize();
  3. The call of garbage collection mechanism is determined by the system (that is, it has its own GC algorithm) or through system GC () actively triggers the garbage collection mechanism (not necessarily successful).

Tip: in actual development, finalize() is hardly used, so it is mainly to cope with the interview

public class Finalize_ {
    public static void main(String[] args) {
        Car car = new Car("bmw");
        //Execute to car = null; The car object is garbage, and the garbage collector will recycle (destroy) the object
        //Before destroying an object, it will call finalize() of the object
        //Programmers can write their own business logic code in finalize(), such as releasing resources: database connections, or open files
        //If the programmer does not override finalize(), then he will call finalize() of the Object class, which is the default processing
        //If programmers rewrite finalize(), they can implement their own logic
        car = null;
        System.gc();    //Actively calling the garbage collector may not trigger successfully

        System.out.println("The program exited...");
    }
}

class Car {
    private String name;

    public Car(String name) {
        this.name = name;
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("We destroy cars:" + name);
        System.out.println("We released some resources...");
//        super.finalize();
    }
}

//The program output is as follows, due to system After GC () is called, the program will not block here, so it will not be a simple sequential output
/*
The program exited
 We destroy cars: BMW
 We released some resources
*/

Topics: Java Back-end