[JAVA Language Learning]Chapter 08 Object-Oriented Programming (Intermediate Part) (P263 - P361)

Han Shunping Learn Java in 30 days with zero foundation study notes

Chapter 08 Object-Oriented Programming (Intermediate Part) (P263 - P361)

Eclipse shortcut keys: Eclipse Shortcuts | Rookie Tutorial (runoob.com)

8.1 package

  • The three functions of the package

    • Differentiate between classes with the same name
    • When there are many classes, the classes can be well managed
    • Control Access Scope
  • basic grammar

    package com.hspedu;

    • package keyword, which means packaging
    • com.hspedu represents the package name
  • The essence of the package is actually to create different folders/directories to hold class files

  • Package naming: only numbers, letters, underscores, and dots can be included. But it cannot start with a number, and cannot be a keyword or reserved word. Generally com.company name.project name.business module name

  • commonly used package

    A package contains many classes. The commonly used packages in java are:

    1. java.lang.* //lang package is the basic package, imported by default, no need to import again.
    2. java.util.* //util package, toolkit provided by the system, tool class, using Scanner
    3. java.net.* //network package, web development
    4. java.awt.* // is to do java interface development, GUI
  • The introduction of the package: import

    Just import which class you need to use. It is not recommended to use * import

  • The function of package is to declare the package where the current class is located. It needs to be placed at the top of the class (or file). There is only one sentence of package in a class.

8.2 Access modifiers (important)

java provides four access control modifier symbols for controlling the access (scope) of methods and properties (member variables):

  1. Public level: Modified with public, open to the public
  2. Protected level: modified with protected, open to subclasses and classes in the same package
  3. Default level: no modifiers, exposed to classes in the same package.
  4. Private level: Modified with private, only the class itself can access, not open to the outside world.
  • access range

    access levelaccess modifiersimilarSame bagSubclassdifferent packages
    publicpublic
    protectedprotected×
    defaultno modifiers××
    privateprivate×××
  • Precautions

    • Modifiers can be used to modify properties, member methods and classes in a class
    • Only the default and public can modify the class, and follow the characteristics of the above access rights
    • Access rules for member methods are exactly the same as for properties

8.3 Encapsulation (one of the three major characteristics of OPP)

Encapsulation (encapsulation) is to encapsulate the abstracted data [attribute] and the operation [method] on the data together, the data is protected inside, and other parts of the program can only operate on the data through the authorized operation [method]. ;

  • benefit

    • Hide implementation details: method(connect to database) <-- call(pass in parameters...)
    • Data can be verified to ensure safety and reasonableness
  • Implementation steps

    1. Make the property private (you cannot directly modify the property)

    2. Provide a public (public) set method for judging and assigning values ​​to attributes

      public void setXxx(type parameter name) { // Xxx represents an attribute
      	// Add business logic for data validation
      	Attributes = parameter name;
      }
      
    3. Provide a public (public) get method for getting the value of the property

      public type of data getXxx(type parameter name) { // Permission judgment, Xxx represents a certain attribute
      	return xx;
      }
      

8.4 Inheritance (one of the three major characteristics of OPP)

Inheritance can solve code reuse and make our programming closer to human thinking. When multiple classes have the same attributes (variables) and methods, the parent class can be abstracted from these classes, and these same attributes and methods can be defined in the parent class. All subclasses do not need to redefine these attributes and methods. You only need to declare the inheritance of the parent class through extends.

  • basic grammar

    class child class extends parent class {}

    • The parent class will automatically have the properties and methods defined by the parent class
    • The parent class is also called the super class, the base class
    • subclass
  • advantage

    1. Increased code reusability
    2. Code scalability and maintainability are improved
  • Notes and Details

    • Subclasses inherit all properties and methods. Non-private properties and methods can be directly accessed in subclasses, but private properties and methods cannot be directly accessed in subclasses. Public methods must be provided by the parent class to access
    • 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 no-argument constructor of the parent class will always be called by default; if the parent class does not provide a no-argument constructor, it must be in the constructor of the subclass Use super to specify which constructor of the parent class is used to complete the initialization of the parent class, otherwise, the compilation will not pass (how to understand.)
    • If you want to specify to call a constructor of the parent class, call it explicitly: super( parameter list)
    • When super is used, it must be placed on the first line of the constructor (super can only be used in the constructor)
    • Both super() and this() can only be placed on the first line of the constructor, so these two methods cannot coexist in a constructor
    • All classes in java are subclasses of the Object class, and Object is the base class of all classes.
    • Calls to superclass constructors are not limited to direct superclasses! will be traced all the way up to the Object class (top-level parent class)
    • A subclass can only inherit at most one parent class (referring to direct inheritance), that is, a single inheritance mechanism in java.
      Thinking: How to let class A inherit class B and class C? [A inherits B, B inherits C]
    • Inheritance cannot be abused, and the logical relationship of is-a must be satisfied between the subclass and the parent class
  • Inherit the essence

    find find relationship

    (1) First check whether the subclass has this attribute
    (2) If the subclass has this attribute and can access it, return the information
    (3) 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 can access it, return information...)
    (4) If the parent class does not exist, follow the rule of (3) and continue to find the parent class until Object...

  • practise

this and super cannot co-exist

Super keyword

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

  • basic grammar

    • Access the properties of the parent class, but not the private properties of the parent class: super.property name;
    • To access the method of the parent class, you cannot access the private method of the parent class: super. method name (parameter list);
    • Access the constructor of the parent class: super( parameter list); (can only be placed in the first sentence of the constructor, and only one sentence can appear)
  • detail

    • The access of super is not limited to the direct parent class. If there are members with the same name in the grandpa class and this class, you can also use super to access the members of the grandpa class; if there are members with the same name in multiple base classes (superior classes), use super Access follows the principle of proximity. A->B->C

    • I want to call the cal method of the parent class-A. At this time, because the subclass B has no cal method, I can use the following three methods. When looking for the cal method (cal() and this.cal()), the order is:
      (1) Find this class first, if there is, call
      (2) If not, find the parent class (if there is and can be called, then call)
      (3) If there is no parent class, continue to find the parent class of the parent class, the whole rule is the same, until the Object class
      Tip: If the method is found but cannot be accessed, an error will be reported, cannot access; if the method is not found during the method search, it will be prompted that the method does not exist

      Same rules for accessing properties

    • When the subclass has the same name as the member (property and method) in the parent class, in order to access the members of the parent class, you must pass super. If there is no duplicate name, using super, this, and direct access has the same effect.

  • Comparison of super and this

    No.point of differencethissuper
    1call attributeAccess the attributes in this class, if there is no such attribute in this class, continue to search from the parent classFind attributes starting from the parent class
    2call methodAccess the method in this class, if there is no such method in this class, continue to search from the parent classFind methods starting from the parent class
    3call constructorCalling the constructor of this class must be placed in the first line of the constructorCalling the parent class constructor must be placed in the first line of the subclass constructor
    4specialrepresents the current objectAccess parent class object in subclass

Method rewriting (Overwrite)

If the subclass has a method that has the same name, return type, and parameters as a method of the parent class, then the method of the subclass overrides the method of the parent class.

  • Precautions

    • The formal parameter list and method name of the method of the subclass must be exactly the same as the formal parameter list and method name of the parent class method

    • The return type of the subclass method is the same as the return type of the parent class or a subclass of the return type of the parent class

      Example: The return type of the parent class is Object, and the return type of the subclass is String (String is a subclass of Object)

      Parent class: public Object getInfo(){} Subclass: public String getInfo(){}

    • Subclass methods cannot narrow the access rights of parent class methods (public -> protected -> default -> private)

      The parent class is protected, while the subclass is public, you can

      The parent class is public, and the subclass is protected, no, it is reduced

  • Method Overriding and Method Overloading

    nameRange of occurrencemethod nameparameter listreturn typeModifier
    overloadThis categorymust be the sameThere is at least one difference in type, number, and orderno requestno request
    rewriteparent-child classmust be the samesameThe method overridden by the subclass returns the same type as the parent class, or its subclassSubclass methods cannot narrow the access scope of parent class methods

8.5 Polymorphism (one of the three major characteristics of OPP)

A method or object has many forms. It is the third major feature of object-oriented, and polymorphism is based on encapsulation and inheritance.

  • example

    The owner feeds the animals. The feeding method can have many animals and a lot of food. The code reusability is not high, which is not conducive to code maintenance.

    Using polymorphism, you can manage the feeding problem of the master in a unified manner.

    public class Animal {
    	public void cry() {
    		System.out.println("Animal cry() animals are calling....");
    	}
    }
    -------------------------------------------------------------
    public class Cat extends Animal {
        public void cry() {
        	System.out.println("Cat cry() kitten meowing...");
        }
    }
    -------------------------------------------------------------
    public class Dog extends Animal {
        public void cry() {
    		System.out.println("Dog cry() puppy barking...");
    	}
    }
    -------------------------------------------------------------
    public class PolyObject {
        public static void main(String[] args) {
        	//Experience object polymorphism
        	//animal The compilation type is Animal, and the running type is Dog
        	Animal animal = new Dog();
        	//Because the running type of animal is Dog when it is executed until the line is changed, so cry is the cry of Dog
        	animal.cry(); //puppy barking
        	//animal The compilation type is Animal, and the running type is Cat
        	animal = new Cat();
        	animal.cry(); //kitten meowing
        }
    }
    
  • The embodiment of polymorphism

    • method polymorphism
      • Overloading: when different parameters are passed in, different methods will be called
      • Rewrite: The corresponding method will be automatically located
    • object polymorphism
      • An object's compile type and run type can be inconsistent
      • The compilation type is determined when the object is defined and cannot be changed
      • The type of operation can be changed
      • When compiling the type, look at the left side of the = sign, and when running the type, look at the right side of the = sign
  • The premise of polymorphism is: there is an inheritance relationship between two objects (classes)

  • polymorphic upcasting

    • Essence: The reference of the parent class points to the object of the subclass
    • Syntax: superclass type reference name = new subclass type();
    • Features:
      • The compile type is on the left, and the running type is on the right
      • All members in the parent class can be called (subject to access permissions)
      • Cannot call specific members in subclasses
      • The final running effect depends on the specific implementation of the subclass
  • polymorphic downcasting

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

    • Only the reference of the parent class can be forcibly transferred, but the object of the parent class cannot be forcibly transferred

    • It is required that the reference of the parent class must point to an object of the current target type

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

      After the upward transformation, the members of the subclass cannot be obtained. Then through downcasting, call subclass members

public class Animal {
    String name = "animal";
    int age = 10;
    public void sleep(){
    	System.out.println("sleep");
    }
    public void run(){
        System.out.println("run");
    }

    public void eat(){
        System.out.println("eat");
    }
    public void show(){
        System.out.println("hello,Hello");
    }
}
----------------------------------------------------------------
public class Cat extends Animal {
    public void eat(){//method override
    	System.out.println("cat eats fish");
    }
    public void catchMouse(){//Cat specific methods
    	System.out.println("cat catches mouse");
    }
}
----------------------------------------------------------------
public class Dog extends Animal {//Dog is a subclass of Animal
}
----------------------------------------------------------------
public class PolyDetail {
    public static void main(String[] args) {
	
        // Upward transformation: the reference of the parent class points to the object of the subclass
		// Syntax: parent class type reference name = new subclass type();
		Animal animal = new Cat();
		Object obj = new Cat();//Is it possible? Yes, Object is also the parent class of Cat
        
        //The rules for upcasting calling methods are as follows:
        // (1) All members in the parent class can be called (subject to access rights)
        // (2) But you cannot call the unique members of the subclass
        // (#)Because in the compilation phase, which members can be called is determined by the compilation type
        // animal.catchMouse(); error
        // (4) The final running effect depends on the specific implementation of the subclass (running type), that is, when calling a method, search for the method starting from the subclass (running type)
        // , and then call, the rules are consistent with the method call rules I mentioned earlier.
        animal.eat();    // Cat eats fish..
        animal.run();    // run
        animal.show();   // hello, hello
        animal.sleep();  // sleep

        // Call Cat's catchMouse method
        // Downward transformation
        // (1) Grammar: subclass type reference name = (subclass type) parent class reference;
        //Ask a question? The compilation type of cat is Cat, and the running type is Cat
        Cat cat = (Cat) animal;
        cat.catchMouse();//cat catches mouse
        // (2) It is required that the reference of the parent class must point to the object of the current target type
        Dog dog = (Dog) animal; //May I?
        // No, because animal originally points to cats, so it can only point to cats
        System.out.println("ok~~");
	}
}
  • Notes and Details

    • There is no rewriting of attributes! The value of the attribute depends on the compilation type

    • instanceOf comparison operator, used to determine whether the running type of the object is XX type or a subtype of XX type

      System.out.println(bb instanceof BB);

  • practise

    The attribute depends on compilation, and the method depends on operation?

java's dynamic binding mechanism (very, very important)

Important features of Java: dynamic binding mechanism

  • When calling an object method, the method will be bound to the memory address/running type of the object
  • When calling object properties, there is no dynamic binding mechanism, where to declare, where to use

When the sum method of class B is commented out, the sum method of class A is executed, and then getI() of class B is executed, so 30+10=40 is returned. When the sum1 method of class B is commented out, the sum method of class A is executed. At this time, i = 10, so 10+10=20 is returned.

polymorphic application

  • polymorphic array

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

    public class Person {//father
        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 and age
        	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;
        }
        //Rewrite the parent class say
        @Override
        public String say() {
        	return "student" + super.say() + " score=" + score;
        }
        //unique method
        public void study() {
        	System.out.println("student" + getName() + " learning java...");
        }
    }
    
    -------------------------------------------------------------
    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;
        }
        //Write and override the say method of the parent class
        @Override
        public String say() {
        	return "teacher" + super.say() + " salary=" + salary;
        }
        //unique method
        public void teach() {
        	System.out.println("teacher" + getName() + " is speaking java course...");
        }
    }
    -------------------------------------------------------------
    public class PloyArray {
        public static void main(String[] args) {
            //Application example: An existing inheritance structure is as follows: it is required to create a Person object,
            // 2 Student objects and 2 Teacher objects, put them in the array uniformly, and call the say method of each object
            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);
            //Loop through the polymorphic array, call say
            for (int i = 0; i < persons.length; i++) {
            //The teacher reminds: person[i] compile type is Person, and the running type is judged according to the actual situation with JVM
                System.out.println(persons[i].say());//dynamic binding mechanism
                //Everyone is smart here. Use type judgment + downcasting.
                if(persons[i] instanceof Student) {//Determine whether the operation type of person[i] is Student
                    Student student = (Student)persons[i];//Downward transformation
                    student.study();
                    //Friends can also use a statement ((Student)persons[i]).study();
                } else if(persons[i] instanceof Teacher) {
                    Teacher teacher = (Teacher)persons[i];
                    teacher.teach();
                } else if(persons[i] instanceof Person){
                    //System.out.println("Your type is wrong, please check yourself...");
                } else {
                    System.out.println("your type is wrong, please check yourself...");
                }
            }
        }
    }
    
  • polymorphic parameters

    The formal parameter type of the method definition is the parent class type, and the actual parameter type is allowed to be the subclass type

    package test.ploy;
    
    public class Employee {
    	private String name;
    	private double salary;
    	
    	public Employee(String name, double salary) {
    		super();
    		this.name = name;
    		this.salary = salary;
    	}
    
    	public double getAnnual() {
    		return salary * 12;
    	}
    	
    	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;
    	}
    }
    ---------------------------------------------------------
    package test.ploy;
    
    public class Manager extends Employee {
    	
    	private double bonus;
    	
    	public Manager(String name, double salary, double bonus) {
    		super(name, salary);
    		// TODO Auto-generated constructor stub
    		this.bonus = bonus;
    	}
    	
    	public void manage() {
    		System.out.println("manager " + getName() + " is working");
    	}
    
    	public double getBonus() {
    		return bonus;
    	}
    
    	public void setBonus(double bonus) {
    		this.bonus = bonus;
    	}
    	
    	@Override
    	public double getAnnual() {
    		return super.getAnnual() + bonus;
    	}
    	
    }   
    -------------------------------------------------------------
    package test.ploy;
    
    public class Worker extends Employee {
    	
    	public Worker(String name, double salary) {
    		super(name, salary);
    		// TODO Auto-generated constructor stub
    	}
    
    	public void work() {
    		System.out.println("General staff " + getName() + " is working");
    	}
    	
    	@Override
    	public double getAnnual() {
    		return super.getAnnual();
    	}
    }
    -------------------------------------------------------------
    package test.ploy;
    
    public class Test {
    
    	public static void main(String[] args) {
    		
    		Test t = new Test();
    		Worker tom = new Worker("tom", 2500);
    		Manager milan = new Manager("milan", 5000, 200000);
    		t.showEmpAnnual(tom);
    		t.showEmpAnnual(milan);
    		
    		t.testWork(tom);
    		t.testWork(milan);
    	}
    	
    	public void showEmpAnnual(Employee e) {
    		System.out.println(e.getAnnual());
    	}
    	
    	public void testWork(Employee e) {
    		if(e instanceof Worker) {
    			((Worker) e).work();  // Downward transformation
    		} else if(e instanceof Manager){
    			((Manager) e).manage();
    		} else {
    			System.out.println("hhhhhhh");
    		}
    	}
    }
    

8.6 Detailed Explanation of Object Class, Garbage Collection Mechanism

All classes (including arrays) are methods of this class

equals method

  • == vs. equals

    • ==

      is a comparison operator

      • Both the basic type and the reference type can be judged
      • If the basic type is judged, the judgment is whether the values ​​are equal, and the types are not compared
      • If you judge the reference type, you judge whether the addresses are equal
    • equals

      • It is a method in the Object class, which can only judge the reference type

        equals method, how to view the source code: put the cursor on the equals method, and directly enter ctrl+b. If you can't use it. Configure it yourself. You can use it

      • The default judgment is whether the addresses are equal, and this method is often rewritten in subclasses to judge whether the contents are equal. Such as Integer, String

  • practise

hashCode() method

  1. Improve the efficiency of containers with hash structures!
  2. Two references, if they point to the same object, must have the same hash value!
  3. Two references, if they point to different objects, the hash values ​​are different
  4. The hash value is mainly based on the address number! A hash value cannot be fully equated to an address.
  5. Later in the collection hashCode will also be rewritten if necessary

toString() method

  1. Basic introduction, returns a string representation of an object
    Default return: full class name + @ + hexadecimal hash value
    Subclasses often override the toString method to return the attribute information of the object
  2. Override the toString method, when printing objects or splicing objects, the toString form of the object will be called automatically.
  3. When directly outputting an object, the toString method will be called by default, such as System.out.println(monster); it will call monster.toString() by default

finalize() method

This method is called by an object's garbage collector when the garbage collector determines that there are no more references to the object

  1. When an object is recycled, the system automatically calls the object's finalize method. Subclasses can override this method to do some operations to release resources.

  2. When is it recycled: When an object does not have any references, the jvm considers the object to be a garbage object and uses the garbage collection mechanism. To destroy the object, the finalize method will be called before destroying the object.

  3. The call of the garbage collection mechanism is determined by the system (that is, it has its own GC algorithm), or it can actively trigger the garbage collection mechanism through System.gc()

    In actual development, finalize is almost never used, so it is more for interviews.

8.7 Breakpoint debugging

In the process of breakpoint debugging, it is the running state, which is executed according to the running type of the object.

  • hot key
    F7 (jump in) F8 (skip) shift+F8 (jump out) F9(resume, execute to the next breakpoint)
    F7: jump into the method
    F8: Execute code line by line.
    shift+F8: Jump out of the method

Tags: Java

Posted by plezops on Thu, 19 Jan 2023 05:37:02 +1030