Java note 7 object oriented programming (intermediate)

7.1 package

The essence of a package is actually to create different folders / directories to hold class files

7.1.1 naming rules

  • It can only contain numbers, letters, underscores and small dots, However, it cannot start with a number, keyword or reserved word
  • com. Company name. Project name Business module name

7.1.2 common packages

  • java.lang.* //lang is the default package. It is imported by default and does not need to be imported again
  • java.util.* //util package, toolkit provided by the system, tool class
  • java.net.* // Network package, network development
  • java.awt.* //java interface development, GUI

7.2 access modifier

7.2.1 basic introduction

java provides four access control modifiers to control the access rights (SCOPE) of methods and attributes (member variables):

  • Public level: decorated with public, open to the public
  • Protected level: modified with protected and exposed to subclasses and classes in the same package
  • Default level: open to classes in the same package without modifiers
  • Private level: decorated with private, only the class itself can be accessed and not disclosed

7.2.2 access scope of four access modifiers

7.2.3 precautions

  1. Modifiers can be used to modify properties, member methods, and classes in a class
  2. Only public and default can modify classes and comply with the above access rights
  3. Access rights in subclasses are placed in the inheritance section
  4. The access rules of member methods are the same as those of properties

7.3 encapsulation of three features of object-oriented programming

7.3.1 introduction

encapsulation is to encapsulate the abstract data [attribute] and the operation [method] of the data. The data is protected internally. Other parts of the program can operate the data only through the authorized operation [method].

7.3.2 understanding of packaging

  • Hide implementation details: method (connect to database) < = = call (pass in parameters...)

  • The data can be verified to ensure safety and rationality

7.3.3 implementation steps of packaging (three steps)

  • Privatize attributes [cannot modify attributes directly]
  • Provides a public set method
  • Provide a public get method

7.3.4 combination of constructor and set method

  • It's best to use the set method to modify properties in the constructor

7.4 inheritance of three characteristics of object-oriented programming

7.4.1 introduction

  • Inheritance can solve code reuse and make our programming closer to human thinking. When multiple classes have the same attributes and methods, you can abstract the parent class from these classes and define these same attributes and methods in the parent class. All subclasses do not need to redefine these attributes and methods, but only need to declare the inherited parent class through extensions

  • The parent class is also called super class and base class; Subclasses are also called derived classes

  • Inheritance diagram

  • Using inheritance can improve the reusability, expansibility and maintainability of code

7.4.2 use details!

  • Subclasses inherit all properties and methods. Non private properties and methods can be accessed directly in subclasses, but private properties and methods cannot be accessed directly in subclasses. They should be accessed through the public methods provided by the parent class
  • The subclass must call the constructor of the parent class to complete the initialization of the parent class
  • When creating a subclass object, no matter which constructor of the subclass is used, the parameterless constructor of the parent class (super();) is always called by default, If the parent class does not provide a parameterless constructor, you must use super (parameter list) in the constructor in the child class; To specify which constructor of the parent class is used to complete the initialization of the parent class. Otherwise, the compilation will not pass
  • If you want to specify a constructor to call the parent class, call it explicitly: Super (parameter list);
  • super(); When using, it must be placed on the first line of the constructor (super(); (only used in constructors)
  • super(); And this(); They can only be placed on the first line of the constructor, so the two methods cannot share the same constructor
  • All classes in Java are subclasses of the Object class, which is the base class of all classes
  • The call of the parent class constructor is not limited to the direct parent class, but will be traced back to the Object class (top-level parent class)
  • It can only inherit directly from a single parent class (that is, a single child class)
  • The parent and child classes of is-a must not be inherited directly

7.4.3 analysis of the essence of inheritance!

  • Load Object class, GrandPa class, Father class and Son class in turn
  • When accessing properties, the information should be returned according to the search relationship
    • First look at the attribute of the subclass and whether it exists
    • If the subclass has this property and can be accessed, information is returned
    • If the subclass does not have this attribute, it depends on whether the parent class has this attribute (if the parent class has this attribute and is accessible, it returns information)
    • If there is no parent class, continue to look up and know the Object. If there is no error, return
    • Properties that cannot be accessed in the parent class can be accessed through public methods provided by the parent class
    • The attribute in the parent class is private. The attribute is public in the parent class of the parent class, and the subclass cannot be accessed directly. If it is found to be private when accessing the parent class, an error will be reported directly

7.4.4 inheritance practice

public class Test {
    public static void main(String[] args) {
        C c = new C();
    }
}

class A {
    public A() {
        System.out.println("I am A class");
    }
}

class B extends A {
    public B() {
        System.out.println("I am B Nonparametric construction of class");
    }

    public B(String name) {
        System.out.println(name + "I am B Parametric construction of class");
    }
}

class C extends B { //Class C, inheriting class B
    public C() {
        this("hello");
        System.out.println("I am c Nonparametric construction of class");
    }

    public C(String name) {
        super("hahah");
        System.out.println("I am c Parametric construction of class");
    }
}
/*Output:
I'm class A
hahah I'm a parametric construct of class B
 I am a parametric construct of class c
 I am a nonparametric construct of class c
 */

7.5 super keyword

7.5.1 introduction

  • super represents the reference of the parent class and is used to access the properties, methods and constructors of the parent class

7.5.2 convenience / details brought by super to programming

  • Benefits of calling the parent constructor

    • The division of labor is clear. The parent class attribute is initialized by the parent class and the child class attribute is initialized by the child class
  • When a child class has the same name as a member (property and method) in the parent class, in order to access the member of the parent class, you must pass super; If there is no duplicate name, using super, this and direct access will have the same effect

  • Super's access is not limited to the direct parent class. If there are members with the same name in the grandfather class and this class, you can also use super to access the members of the grandfather class; If there are members with the same name in multiple base classes, using super access follows the proximity principle and the rules of access permission

7.5.3 comparison between super and this

Distinguishing pointsthissuper
Access propertiesAccess the attribute in this class. If this class does not have this attribute, continue to find it from the parent classFind properties from parent class
Call methodAccess the method in this class. If this class does not have this method, continue to find it from the parent classFind method from parent class
Invoking Constructors Calling this class constructor must be placed on the first line of the constructorCalling the parent class constructor must be placed on the first line of the child class constructor
specialRepresents the current objectAccessing parent objects in subclasses

7.6 method override

7.6.1 introduction

  • Method override means that a method in a subclass has the same name, return type and parameters as a method of the parent class. Then we say that the method of the subclass overrides the method of the parent class

7.6.2 use details

  • The formal parameter list and method name of the method of the subclass should be exactly the same as that of the parent class
  • 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
    • For example, the return type of the parent class method is Object, and the return type of the child class method is String
  • Subclass methods cannot reduce the access rights of parent methods
    • Public > protected > Default > private

7.6.3 difference between rewriting and overloading

nameOccurrence rangeMethod nameparameter list Return typeModifier
overloadThis categoryMust be the sameThere is at least one difference in type, number or orderNo requirementNo requirement
overrideParent child classMust be the sameidenticalThe subclass overrides the method. The return type is the same as that of the parent method, or it is its subclassMethods of subclasses cannot narrow the access scope of parent methods

7.7 polymorphism of three characteristics of object-oriented programming

7.7.1 introduction to multiple polymorphisms

Methods or objects have multiple forms. Polymorphism is one of the three characteristics of object-oriented. Polymorphism is based on encapsulation and inheritance

7.7.1.1 polymorphism of methods

public class Test {
    public static void main(String[] args) {
        //Method overloading reflects polymorphism
        A a = new A();
        //Here, if we pass in different parameters, we will get different sum methods, which reflects polymorphism
        System.out.println(a.sum(10, 20));
        System.out.println(a.sum(10, 20, 30));

        //Method rewriting reflects polymorphism
        B b = new B();
        //Different objects call different say() methods, which reflects polymorphism
        a.say();
        b.say();
    }
}
class B {   //Parent class
    public void say() {
        System.out.println("B say()Method called...");
    }
}
class A extends B {
    public int sum(int n1, int n2) {
        return n1 + n2;
    }
    public int sum(int n1, int n2, int n3) {
        return n1 + n2 + n3;
    }

    public void say() {
        System.out.println("A say()Method called...");
    }
}

7.7.7.2 polymorphism of objects

Important note:

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

    1. Animal animal = new Dog();
    2. A reference of the parent class points to an object of the child class
    3. The compile type of animal is animal and the run type is Dog
  2. The compilation type is determined when defining the object and cannot be changed

  3. The operation type can be changed

    1. animal = new Cat();
    2. The running type of animal has changed to Cat, and the compilation type is still animal
  4. The compilation type is to the left of the = sign when defining, and the running type is to the right of the = sign

give an example

public class Test {
    public static void main(String[] args) {
        //Characteristics of experience object polymorphism
        Animal animal = new Dog();
        //Compile type: Animal, run type: Dog
        animal.cry();   //Dog cry

        animal = new Cat();
        //The compile type of animal remains unchanged and the run type changes to Cat
        animal.cry();   //Cat cry
    }
}
class Animal {
    public void cry() {
        System.out.println("Animals are barking...");
    }
}
class Cat extends Animal {
    @Override
    public void cry() {
        System.out.println("Cat cry() kittens mew ...");
    }
}
class Dog extends Animal {
    @Override
    public void cry() {
        System.out.println("Dog cry() The dog barked...");
    }
}

7.7.2 introduction cases

public class Animal {
    private String name;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
}
public class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
}
public class Food {
    private String name;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
public class Fish extends Food {
    public Fish(String name) {
        super(name);
    }
}
public class Bone extends Food {
    public Bone(String name) {
        super(name);
    }
}
public class Master {
    private String name;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    //The use of polymorphism mechanism can uniformly manage the feeding problem of the host
    //The compilation type of Animal is Animal, which can point to (receive) objects of subclasses of Animal
    //Food compilation type is food, which can point to (receive) the object of food subclass
    public void feed(Animal animal, Food food) {
        System.out.println("master " + name + " to " + animal.getName() + " eat " + food.getName());
    }

    //The owner fed the dog bones
//    public void feed(Dog dog, Bone bone) {
//        System.out.println("master" + name + "give" + dog.getName() + "eat" + bone getName());
//    }
//    //The owner fed the kitten yellow croaker
//    public void feed(Cat cat, Fish fish) {
//        System.out.println("master" + name + "give" + cat.getName() + "eat" + fish getName());
//    }

    //If there are many animals, there is a lot of food
    //===>There are many feed methods, which are not conducive to management and maintenance
    //Pig --> Rice
    //Tiger ---> meat ...
    //...

}
public class Poly01 {
    public static void main(String[] args) {

        Master tom = new Master("Tom");
        Dog dog = new Dog("chinese rhubarb~");
        Bone bone = new Bone("Big stick bone~");
        tom.feed(dog, bone);

        Cat cat = new Cat("Kitten~");
        Fish fish = new Fish("Yellow croaker~");
        System.out.println("===========-------");
        tom.feed(cat, fish);

        //Add to the pig for rice
        Pig pig = new Pig("Floret pig");
        Rice rice = new Rice("rice");
        System.out.println("===================");
        tom.feed(pig, rice);
    }
}

7.7.3 precautions

The premise is that there is an inheritance relationship between the two objects (classes)

7.7.3.1 upward transformation of polymorphism

Essence: the reference of the parent class points to the object of the child class

Syntax: parent type reference name = new subclass type ();

characteristic:

  • 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 rules)
  • A unique member of a subclass cannot be called
    • Because in the compilation stage, which members can be called is determined by the compilation type
  • The final running effect depends on the specific implementation of subclasses
    • That is, when the method is invoked, the search method starts from the subclass and then calls, and the rule is consistent with the method call rule written in front.

7.7.3.2 polymorphic upward transformation

Syntax: subclass type reference name = (subclass type) parent class reference;

characteristic:

  • 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 an object of the current target type

  • After the downward transformation, all members in the subclass type can be called

  • Property is not rewritten! The value of the attribute depends on the compilation type

  • public class PolyDetail02 {
    	public static void main(String[] args) {
    		//Property is not rewritten! The value of the attribute depends on the compilation type
    		Base base = new Sub();//Upward transformation
    		System.out.println(base.count);// ?  See compilation type 10
    		Sub sub = new Sub();
    		System.out.println(sub.count);//? 20
    	}
    }
    class Base { //Parent class
    	int count = 10;//attribute
    }
    class Sub extends Base {//Subclass
    	int count = 20;//attribute
    }
    
  • instanceOf comparison operator, which is used to judge whether the running type of the object is XX type or a subtype of XX type

    • public class PolyDetail03 {
      	public static void main(String[] args) {
      		BB bb = new BB();
      		System.out.println(bb instanceof BB);// true
      		System.out.println(bb instanceof AA);// true
      		//Aacompile type AA, run type BB
      		//BB is subclass AA
      		AA aa = new BB();
      		System.out.println(aa instanceof AA);//true
      		System.out.println(aa instanceof BB);//true
      		Object obj = new Object();
      		System.out.println(obj instanceof AA);//false
      		String str = "hello";
      		//System.out.println(str instanceof AA);
      		System.out.println(str instanceof Object);//true
      	}
      }
      class AA {} //Parent class
      class BB extends AA {}//Subclass
      

7.7.4 polymorphism exercise

public class PolyExer01 {
    public static void main(String[] args) {
        double d = 13.4;	//ok
        long l = (long)d;	//ok
        System.out.println(l);	//13
        int in = 5;	//ok
        boolean b = (boolean)in;	//error boolean -> int
        Object obj = "hello";	//ok upward transformation
        String objStr = (String)obj;	//ok downward transformation
        System.out.println(objStr);	//hello
        Object objPri = new Integer(5);	//ok upward transformation
        String str = (String)objPri;	//error the parent class reference to Integer is converted to String
        Integer str1 = (Integer)objPri;	//ok downward transformation
    }
}
public class PolyExer02 {
    public static void main(String[] args) {
        Sub s = new Sub();
        System.out.println(s.count);	//20
        s.display();	//20
        Base b = s;
        System.out.println(b == s);	//true
        System.out.println(b.count);	//10
        b.display;	//20
    }
}
class Base {
    int count = 10;
    public void display() {
        System.out.println(this.count);
    }
}
class Sub extends Base {
    int count = 20;
    public void display() {
        System.out.println(this.count);
    }
}

7.7.5 dynamic binding mechanism of java!!!

  1. When an object method is called, the method will be bound to the memory address / run type of the object
  2. When calling object properties, there is no dynamic binding mechanism. Where to declare and where to use
public class Test {
    public static void main(String[] args) {
        A a = new B();
        System.out.println(a.sum());    //The sum() of class B is output 40 before annotation and 30 after annotation
        System.out.println(a.sum1());   //Class B sum1() outputs 30 before annotation and 20 after annotation
    }
}

class A {
    public int i = 10;
    //When an object method is called, the method will be bound to the memory address / run type of the object
    //The running type of a is class B. call the getI() method of class B
    public int sum() {
        return getI() + 10;
    }
    //When calling object properties, there is no dynamic binding mechanism. Where to declare and where to use
    //i here is declared at compile time for class A, so the value is 10
    public int sum1() {
        return i + 10;
    }
    public int getI() {
        return i;
    }
}
class B extends A {
    public int i = 20;
    /*public int sum() {
        return i + 20;
    }*/
    public  int getI() {
        return i;
    }
    /*public int sum1() {
        return i + 10;
    }*/
}

7.7.6 application of polymorphism

7.7.6.1 polymorphic array

  • Introduction:

  • The definition type of the array is the parent type, and the actual element type saved inside is the subclass type

  • Case:

      1. The existing inheritance structure is as follows: it is required to create one Person object, two Student objects and two Teacher objects, put them in the array, and call the say method of each object
      1. Application instance upgrade: how to call subclass specific methods? For example, how to call a Teacher and a student?
    • public class PolyArray {
          public static void main(String[] args) {
              Person[] persons = new Person[5];
              persons[0] = new Person("jack",20);
              persons[1] = new Student("mary",18,100);
              persons[2] = new Student("smith",19,30.1);
              persons[3] = new Teacher("scott",30,20000);
              persons[4] = new Teacher("king",50,25000);
              for (int i = 0; i < persons.length; i++) {
                  //person[i] the compilation type is person, and the running type is determined by the jvm according to the actual situation
                  System.out.println(persons[i].say());//Dynamic binding mechanism
                  if (persons[i] instanceof Student) {//Judge whether the running type of persons[i] is Student
                      ((Student) persons[i]).study();//Downward transformation
                  } else if (persons[i] instanceof Teacher) {
                      ((Teacher)persons[i]).teach();//Downward transformation
                  }
              }
      
          }
      /*Output result:
      jack	20
      mary	18	score=100.0
       Student mary is studying
      smith	19	score=30.1
       Student smith is studying
      scott	30	salary=20000.0
       Teacher scott is teaching
      king	50	salary=25000.0
       Teacher king is teaching
      */
      
    • public class Person {
          private String name;
          private int age;
      
          public Person(String name, int age) {
              this.name = name;
              this.age = age;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public int getAge() {
              return age;
          }
      
          public void setAge(int age) {
              this.age = age;
          }
      
          public String say() {
              return name + "\t" + age;
          }
      }
      
    • public class Student extends Person {
          private double score;
      
          public Student(String name, int age, double score) {
              super(name, age);
              this.score = score;
          }
      
          public double getScore() {
              return score;
          }
      
          public void setScore(double score) {
              this.score = score;
          }
      
          @Override
          public String say() {
              return super.say() + "\tscore=" + score;
          }
          public void study() {
              System.out.println("student " + getName() + "I am learning...");
          }
      }
      
    • public class Teacher extends Person {
          private double salary;
      
          public Teacher(String name, int age, double salary) {
              super(name, age);
              this.salary = salary;
          }
      
          public double getSalary() {
              return salary;
          }
      
          public void setSalary(double salary) {
              this.salary = salary;
          }
      
          @Override
          public String say() {
              return super.say() + "\tsalary=" + salary;
          }
          public void teach() {
              System.out.println("teacher " + getName() + "Teaching...");
          }
      }
      

7.7.6.2 polymorphic parameters

  • introduce

    • The parameter type is a subclass, and the method type is defined as the parent type
  • case

    1. The owner feeds the animals
    2. Define the Employee class employee, including name and monthly salary [private], as well as the method getAnnual() for calculating annual salary. Ordinary employees and managers inherit employees. Managers have bonus attribute and management method manage(), ordinary employees have method work(), ordinary employees and managers require to rewrite getAnnual() method respectively, and add a method showEmpAnnual(Employee e) to the test class, Achieve the annual salary of any employee object and call this method in main method. Add a method testWork() in the test class. If it is an ordinary employee, call the work () method. If it is a manager, call the manage () method
    • 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();
              System.out.println(tom.getName() + "Your annual salary is" + polyParameter.showEmpAnnual(tom));
              System.out.println(milan.getName() + "Your annual salary is" + polyParameter.showEmpAnnual(milan));
              polyParameter.testWork(tom);
              polyParameter.testWork(milan);
          }
          public double showEmpAnnual(Employee e) {
              return e.getAnnual();
          }
          public void testWork(Employee e) {
              if (e instanceof Worker) {
                  ((Worker)e).work();
              } else if (e instanceof Manager) {
                  ((Manager)e).manage();
              } else {
                  System.out.println("No treatment...");
              }
          }
      }
      /*
      tom Your annual salary is 30000.0
      milan Your annual salary is 260000.0
       Ordinary employee tom is working
       Manager milan is managing
      */
      
    • public class Employee {
          private String name;
          private double salary;
      
          public Employee(String name, double salary) {
              this.name = name;
              this.salary = salary;
          }
      
          public String getName() {
              return name;
          }
      
          public void setName(String name) {
              this.name = name;
          }
      
          public double getSalary() {
              return salary;
          }
      
          public void setSalary(double salary) {
              this.salary = salary;
          }
      
          public double getAnnual() {
              return 12 * salary;
          }
      }
      
    • public class Manager extends Employee {
          private double bonus;
      
          public Manager(String name, double salary, double bonus) {
              super(name, salary);
              this.bonus = bonus;
          }
      
          public double getBonus() {
              return bonus;
          }
      
          public void setBonus(double bonus) {
              this.bonus = bonus;
          }
          public void manage() {
              System.out.println("manager" + getName() + "Managing...");
          }
      
          @Override
          public double getAnnual() {//The manager has an extra bonus
              return super.getAnnual() + bonus;
          }
      }
      
    • public class Worker extends Employee {
          public Worker(String name, double salary) {
              super(name, salary);
          }
          public void work() {
              System.out.println("Ordinary staff" + getName() + "I am working...");
          }
      
          @Override
          public double getAnnual() {//Ordinary employees have no other income, so they can call it directly
              return super.getAnnual();
          }
      }
      

7.8 detailed explanation of object class

7.8.1 equals method

7.8.1.1 equals method

==Comparison with equals:

  1. ==: you can judge both basic types and reference types
    1. If the basic type is judged, the judgment is whether the values are equal. For example: int i = 10;double d = 10.0;
    2. If the reference type is judged, it is judged whether the addresses are equal, that is, whether the same object is judged
  2. equals: it is a method in the Object class and can only judge the reference type
    1. The default judgment is whether the addresses are equal. This method is often overridden in subclasses to judge whether the contents are equal. For example, Integer and String, see the source code

7.8.1.2 rewrite equals method

  1. Judge whether the contents of the two Person objects are equal. If the attribute values of the two Person objects are the same, return true, otherwise false.

    1. public class EqualsExer01 {
          public static void main(String[] args) {
              Person person1 = new Person("jack", 10, 'male');
              Person person2 = new Person("jack", 10, 'male');
              Person person3 = new Person("smith", 10, 'male');
              System.out.println(person1.equals(person2));    //true
              System.out.println(person1.equals(person3));    //false
          }
      }
      class Person {
          private String name;
          private int age;
          private char gender;
      
          public boolean equals(Object obj) {
              if (this == obj) {
                  return true;
              }
              if (obj instanceof Person) {
                  Person obj1 = (Person) obj;
                  return this.name.equals(obj1.name) && this.age == obj1.age && this.gender == obj1.gender;
              }
              return false;
          }
          public Person(String name, int age, char gender) {
              this.name = name;
              this.age = age;
              this.gender = gender;
          }
          public String getName() {
              return name;
          }
          public void setName(String name) {
              this.name = name;
          }
          public int getAge() {
              return age;
          }
          public void setAge(int age) {
              this.age = age;
          }
          public char getGender() {
              return gender;
          }
          public void setGender(char gender) {
              this.gender = gender;
          }
      }
      

7.8.1.3 equals exercises

  1. public class EqualsExer02 {
        public static void main(String[] args) {
            Person_ p1 = new Person_();
            p1.name = "hspedu";
            Person_ p2 = new Person_();
            p2.name = "hspedu";
            System.out.println(p1==p2); //False
            System.out.println(p1.name.equals( p2.name));//T
            System.out.println(p1.equals(p2));//False
            String s1 = new String("asdf");
            String s2 = new String("asdf");
            System.out.println(s1.equals(s2));//T
            System.out.println(s1==s2); //F
        }
    }
    class Person_{//class
        public String name;
    }
    
  2. public class EqualsExer03 {
        public static void main(String[] args) {
            int it = 65;
            float fl = 65.0f;
            System.out.println("65 And 65.0f Are they equal?" + (it == fl));//T
            char ch1 = 'A'; char ch2 = 12;
            System.out.println("65 and'A'Are they equal?" + (it == ch1));//T
            System.out.println("12 and ch2 Are they equal?" + (12 == ch2));//T
            String str1 = new String("hello");
            String str2 = new String("hello");
            System.out.println("str1 and str2 Are they equal?"+ (str1 == str2)); //F
            System.out.println("str1 whether equals str2?"+(str1.equals(str2)));//T
            System.out.println("hello" == new java.sql.Date());//Compilation error
        }
    }
    

7.8.2 hashCode method

7.8.2.1 summary

  1. Improve the efficiency of containers with hash structure
  2. If two references point to the same object, the hash value is the same
  3. If two references point to different objects, the hash values are different
  4. The hash value is converted according to the address number. The hash value cannot be completely equivalent to the address (usually realized by converting the internal address of the object into an integer)
  5. How to override the hashCode method is described in the collection section

7.8.2.2 cases

public class HashCode_ {
    public static void main(String[] args) {
        AA aa = new AA();
        AA aa2 = new AA();
        AA aa3 = aa;
        System.out.println("aa.hashCode()=" + aa.hashCode());//aa.hashCode()=460141958
        System.out.println("aa2.hashCode()=" + aa2.hashCode());//aa2.hashCode()=1163157884
        System.out.println("aa3.hashCode()=" + aa3.hashCode());//aa3.hashCode()=460141958
    }
}
class AA {}

7.8.3 toString method

7.8.3.1 introduction

  • Default return: hexadecimal of full class name + @ + hash value, [view toString method of Object]

  • Subclasses often override the toString method to return the attribute information of the object

  • When the toString method is overridden, the toString form of the object will be automatically called when printing or splicing the object

  • When directly outputting an object, the toString method will be called by default, such as system out. println(monster); Monster will be called by default toString();

7.8.3.2 rewrite toString method

public class ToString_ {
    public static void main(String[] args) {
        /*
        Object toString() source code
        (1)getClass().getName() Full class name of the class (package name + class name)
        (2)Integer.toHexString(hashCode()) Converts the hashCode value of an object to a hexadecimal string
        public String toString() {
            return getClass().getName() + "@" + Integer.toHexString(hashCode());
        }
        */
        Monster monster = new Monster("goblin ", "Mountain patrol", 1000);
        System.out.println(monster.toString());
        //Before overriding the toString method, output toString Monster@1b6d3586
        //1b6d3586 is obtained by converting the hashCode value of the object into hexadecimal
        //After rewriting the toString method, Monster{name = 'monster', job = 'patrol', salary=1000.0}
    }
}
class Monster {
    private String name;
    private String job;
    private double salary;

    public Monster(String name, String job, double salary) {
        this.name = name;
        this.job = job;
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Monster{" +
                "name='" + name + '\'' +
                ", job='" + job + '\'' +
                ", salary=" + salary +
                '}';
    }
}

7.8.4 finalize method

  • When an object is recycled, the system will automatically call the finalize method of the object. Subclasses can override this method to release resources
  • 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 the finalize method
  • The call of garbage collection mechanism is determined by the system (i.e. it has its own GC algorithm) or through system GC () actively triggers garbage collection mechanism
public class Finalize_ {
    public static void main(String[] args) {
        Car bmw = new Car("bmw");
        //At this time, the car object is garbage, and the garbage collector will recycle (destroy) the object. Before destroying the object, it will call the finalize method 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, it will call finalize of the Object class, that is, the default processing
        //If the programmer rewrites finalize, he can implement his own logic
        bmw = null;
        System.gc();//Actively invoke the garbage collector
        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("Some resources were released...");
    }
}
/*Output:
The program exited
 We destroy cars and BMWs
 Released some resources
*/

7.9 breakpoint debug ging

7.9.1 introduction

  1. In the process of breakpoint debugging, it is the runtime state, which is executed according to the running type of the object
  2. Breakpoint debugging refers to setting a breakpoint on a certain line of the program. During debugging, the program will stop when it runs to this line, and then you can debug step by step. During debugging, you can see the current value of each variable. If there is an error, the error will be displayed when debugging to the wrong code line, and stop. Analyze to find the bug
  3. Breakpoint debugging is a skill that programmers must master
  4. Breakpoint debugging can also help us check the execution process of the underlying java source code and improve the Java level of programmers

7.9.2 shortcut keys

F5: enter (jump into the method)

F6: step by step (execute code line by line)

F7: jump out (jump out method)

F8: resume the program and execute to the next breakpoint

7.9.3 application cases

Breakpoint debugging view object creation process

public class Test {
    public static void main(String[] args) {
        //Process for creating objects
        //1. Load Person class information
        //2. Initialization 2.1 default initialization, 2.2 explicit initialization, 2.3 constructor initialization
        //3. Return the address of the object
        Person jack = new Person("jack", 20);
        System.out.println(jack);
    }
}
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Breakpoint debugging to view the working mechanism of dynamic binding

public class Test {
    public static void main(String[] args) {
        A a = new B();
        System.out.println(a.sum());    //The sum() of class B is output 40 before annotation and 30 after annotation
        System.out.println(a.sum1());   //Class B sum1() outputs 30 before annotation and 20 after annotation
    }
}

class A {
    public int i = 10;
    //When an object method is called, the method will be bound to the memory address / run type of the object
    //The running type of a is class B. call the getI() method of class B
    public int sum() {
        return getI() + 10;
    }
    //When calling object properties, there is no dynamic binding mechanism. Where to declare and where to use
    //i here is declared at compile time for class A, so the value is 10
    public int sum1() {
        return i + 10;
    }
    public int getI() {
        return i;
    }
}
class B extends A {
    public int i = 20;
    /*public int sum() {
        return i + 20;
    }*/
    public  int getI() {
        return i;
    }
    /*public int sum1() {
        return i + 10;
    }*/
}

Keywords: Java

Added by netzverwalter on Mon, 07 Mar 2022 17:15:26 +0200