06 - object oriented programming (intermediate part I)

1, Package package

Function of package

1)Distinguish between classes with the same name
2)When there are many classes, you can manage classes well
3)Control access scope

Basic syntax of package

package  com.spock;
explain:
package Keyword, indicating packaging
com.spock Indicates the package name

Naming rules for packages

It can only contain numbers, letters, underscores and small dots, but cannot start with numbers, keywords or reserved words
	demo.class.exec1 //Error, class is a keyword
	demo.12a //Error, 12a starts with a number
	demo.ab12.oa // correct

Package names are generally lowercase+DoT
	com.Company name.Project name.Business module name
	com.sina.blog.user //User module
	com.sina.blog.order //Order module

Common packages

Under one bag,Contains many classes,java The commonly used packages are:

java.lang.* //lang package is a basic package. It is imported by default and does not need to be imported again.
java.util.* //util package, toolkit provided by the system, and tool classes, such as Scanner
java.net.* //Network package, network development
java.awt.* //Is to do Java interface development, GUI

Package introduction

Syntax:
	import package;
The main purpose of introducing a package is to use the classes under the package
 For example:
	import java.util.Scanner; Just introduce a class Scanner
	import java.util.*; Indicates that it will java.util Package all classes are introduced

Use case

package com.hspedu.pkg; 
import java.util.Arrays;
	//be careful:
	
	//Suggestion: we can import whatever class we need to use. It is not recommended to use * import
	//import java.util.Scanner;
	//Indicates that only Java. Net will be introduced Scanner under util package
	//import java.util.*;
	//Indicates that the Java All classes under util package are imported (imported)
	
	public class Import01 {
		public static void main(String[] args) {
			//Use the Arrays provided by the system to sort the array
			int[] arr = {-1, 20, 2, 13, 3};
			//For example, sort them
			//The traditional method is to write your own sorting (bubbling)
			//The system provides related classes to facilitate the completion of Arrays
			Arrays.sort(arr);
			//Output sorting results
			for (int i = 0; i < arr.length ; i++) {
				System.out.print(arr[i] + "\t");
			}
		}
	}
You can import the class you want to use. It is not recommended * Import.
java.lang.* //lang package is a basic package. It is imported by default and does not need to be imported again.

matters needing attention

//The function of package is to declare the package of the current class, which needs to be placed at the top of the class (or file)
// There is at most one package sentence in a class

package com.edu.pkg;

//The import instruction is placed under the package. In front of the class definition, there can be multiple sentences without sequence requirements
import java.util.Scanner;
import java.util.Arrays;
package The function of is to declare the package of the current class, which needs to be placed in the class(Or file)At the top of a class, there is at most one sentence in a class package. 
import The position of the command is package Below, in front of the class definition, there can be multiple sentences without sequence requirements.

2, Access modifier

Basic introduction

Java provides four access control modifiers to control the access rights (SCOPE) of methods and properties (member variables):
1) Public level: decorated with public, open to the public
2) Protected level: modified with protected, and exposed to subclasses and classes in the same package
3) Default level: open to classes in the same package without modifiers
4) Private level: decorated with private, only the class itself can be accessed and not disclosed

Access scope

Access level Access modifier similar Same package Subclass Different packages
open Public
under protection Protected ×
default No modifier × ×
private Private × × ×

matters needing attention

1)Modifiers can be used to modify properties, member methods, and classes in a class.
2)Only default and public Can modify the class, and follow the characteristics of the above access rights
3)The access rules and properties of member methods are exactly the same

3, Three characteristics of object-oriented programming

Object oriented programming has three characteristics: encapsulation, inheritance and polymorphism.

4, Object oriented programming - encapsulation

Basic introduction

Encapsulation is to encapsulate the abstract data [attributes] and the operation [Methods] of the data. The data is protected internally. Other parts of the program can operate the data only through the authorized operation [Methods].

Function of encapsulation

1)Hide implementation details: method (connect to database) <---- Call (pass in parameters)
2)The data can be verified to ensure safety and rationality
	Person {name, age}
	Person p = new Person();
	p.name = "jack";
	p.age = 100;

Implementation steps of encapsulation

1)Privatize properties private [[attribute cannot be modified directly]
2)Provide a public( public)set Method to judge and assign a value to an attribute
	public void setXxx(Type parameter name) {
		//Add business logic for data validation
		attribute = Parameter name;
	}
3)Provide a public( public)get Method to get the value of the property
	public data type getXxx() {
		return xxx;
	}

Use case

class Person {
	public String name; //Public name 
	private int age; //age privatization 
	private double salary; //..
	
	//Constructor alt+insert
	public Person() {
	}

	//It's too slow to write setXxx and getXxx by ourselves. We use the shortcut key alt+insert
	//Then perfect our code according to the requirements
	public String getName() {
		return name;
	}
	public void setName(String name) {
		//Adding data verification is equivalent to adding business logic
		if(name.length() >= 2 && name.length() <=6 ) {
			this.name = name;
		}else {
			System.out.println("The length of the name is incorrect. It needs to be(2-6)Characters, default name");
			this.name = "No celebrity";
		}
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		//judge
		if(age >= 1 && age <= 120) {
			//If it is a reasonable range
			this.age = age;
		} else {
			System.out.println("You set the wrong age, you need to (1-120), Give default age 18 ");
		this.age = 18;//Give a default age
		}
	}
	public double getSalary() {
		//You can add permission judgment for the current object here
		return salary;
   }
   public void setSalary(double salary) {
   		this.salary = salary;
   }
}

5, Object oriented programming - inheritance

Basic introduction

Inheritance can solve code reuse and make our programming closer to human thinking. When multiple classes have the same attributes (variables) 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.

Basic syntax of inheritance

class Subclass extends Parent class {
}

1)Subclasses automatically own the properties and methods defined by the parent class
2)The parent class is also called superclass and base class
3)Subclasses are also called derived classes

The role of inheritance

1)Improve code reusability
2)Improve code scalability and maintainability

Use case

//Student class is the parent class of Pupil and Graduate
public class Student {
	//Common attributes
	public String name;
	public int age;
	private double score;//Achievements / / common methods
	
	public void setScore(double score) {
		this.score = score; 
	}
	public void showInfo() {
		System.out.println("Student name " + name + " Age " + age + " achievement " + score);
	}
}

//Subclass
public class Pupil extends Student { 
	public void testing() {
		System.out.println("pupil " + name + "I'm taking the math test in primary school..");
	} 
}

//Subclass
public class Graduate extends Student {
	public void testing() {  //Not like Pupil
		System.out.println("college student " + name + " I'm taking college math..");
	}
}

Usage details of inheritance

1) Subclasses inherit all properties and methods. Non private properties and methods can be accessed directly in subclasses
 However, private properties and methods cannot be accessed directly in subclasses. They should be accessed through public methods provided by the parent class

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, the parameterless constructor of the parent class is always called by default
 If the parent class does not provide a parameterless constructor, it must be used in the constructor of the child class super To specify that a constructor of the parent class is used to initialize the parent class
 Otherwise, the compilation will not pass
public Sub() {
	//Parameterless constructor
	super(); //The default is to call the parameterless constructor of the parent class, which can be left blank
	System.out.println("Subclass Sub()Constructor called....");
}
4) If you want to specify a constructor to call the parent class, explicitly call it : super(parameter list)
//When creating a subclass object, no matter which constructor of the subclass is used
//By default, the parameterless constructor of the parent class is always called
//If you want to modify, use super to specify

public Sub(String name) {
	super("tom", 30);//Call the constructor of the two parameters of the parent class
	//do nothing...
	System.out.println("Subclass Sub(String name)Constructor called....");
}
5) super When used, it must be placed on the first line of the constructor(super Can only be used in constructors)

6) super() and this() Both methods can only be placed on the first line of the constructor, so the two methods cannot share a constructor

7) java All classes are Object Subclass of class, Object Is the base class of all classes

8) The call of the parent constructor is not limited to the direct parent class! Will go up until Object class(Top level parent)

9) A subclass can inherit at most one parent class(Direct inheritance),Namely java Is a single inheritance mechanism.
Thinking: how to make A Class inheritance B Class and C Class? [ A inherit B, B inherit C]

10) Inheritance cannot be abused, and must be satisfied between subclass and parent is-a Logical relationship. xxx It's a xxx

6, super keyword

Basic introduction

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

Basic grammar

1)Access the properties of the parent class, but cannot access the properties of the parent class private attribute
	super.Attribute name;

2)Access the methods of the parent class, but cannot access the methods of the parent class private method
	super.Method name(parameter list);

3)Constructor to access the parent class
	super(parameter list);
	It can only be placed in the first sentence of the constructor, and only one sentence can appear

Use details of Super

1)Benefits of calling the constructor of the parent class
(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)

2)When there are members in the subclass and the parent class(In order to access the members of the parent class, you must pass super. 
If there is no duplicate name, use super,this,Direct access has the same effect!

3)super The access of 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 it super To access members of the grandpa class;
If multiple base classes(Superior class)There are members with the same name in,use super Visits follow the principle of proximity. A->B->C,Of course, you also need to abide by the relevant rules of access rights.

Comparison between super and this

NO Distinguishing points This Super
1 Access properties Access the attribute in this class. If this class does not have this attribute, continue to find it from the parent class. Find properties from the parent class.
2 Call method Access the method in this class. If this class does not have this method, continue to find it from the parent class. Find methods starting with the parent class.
3 Invoking Constructors Calling the constructor of this class must be placed on the first line of the constructor. Calling the parent class constructor must be placed on the first line of the child class constructor.
4 special Represents the current object Accessing parent objects in subclasses

Note: this blog quotes Mr. Han Shunping's Java course

Added by munsiem on Sun, 09 Jan 2022 07:09:30 +0200