[0 Basic java] Teaching Log: javaSE-Object-Oriented 3

Overview of this chapter

This chapter belongs to the content of Object-Oriented Chapter 2, mainly explaining knowledge points such as this keyword, static keyword, code block, package, import, object-oriented one of the three main features - encapsulation.

1. this keyword

  1. The role of this:
  • this represents the current object itself.
  • More precisely, this represents a reference to the current object.
  1. Use this in common methods
  • Parameters that distinguish class member properties from methods
  • Call other methods of the current object (can be omitted)
  • Location: Any
  1. Use this in construction methods
  • Use this to invoke other construction methods
  • Position: Must be the first statement
  1. this cannot be used with the static method. (After static, you know why!)
  2. this test code
public class TestThis {
	int a,b,c;
	TestThis(){
		System.out.println("Just new One Hello object");
	}
	TestThis(int a,int b){
		//Hello(); // / This way, the constructor cannot be called!
		this(); //Invoke a parameterless construction method and must be on the first line!
		a = a;//This refers to local variables, not member variables
		this.a = a;//This distinguishes member variables from local variables. This accounts for the majority of this usage!
		this.b = b;
	}
	TestThis(int a,int b,int c){
		this(a,b);//Invoke a parameterless construction method and must be on the first line!
		this.c = c;
	}
	void sing(){
	}
	void chifan(){
		this.sing();//sing();
		System.out.println("Your mother told you to go home for dinner!");
	}
	public static void main(String[] args){
		TestThis hi = new TestThis(2,3);
		hi.chifan();
	}
}

7. demo in Classroom

package netclass02;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/1/7 - 01 - 07 - 14:24
 * @Description: netclass02
 * @version: 1.0
 */

/*
 * this:A pointer to the current object
 *        Points to the current object, representing a reference to the current object
 * Purpose:
 *       1,Construction method, where the parameter name in the construction method is the same as the member variable name of the class, this can be used to represent the current object
 *                 Note: With this, you can align the parameters of the constructor with the member variables (following the naming conventions)
 *                 When other construction methods need to be called in a construction method, you can use this (parameter list) to call other construction methods, but it must be in the first line of the method body (rule)
 *       2,In the general method:
 *                 When multiple common methods need to call each other, this can be used to make the call, referring to other methods of the current object
 *       3,How to use when calling member variables:
 *                 Use this when the parameter name in the method is consistent with the member variable. The variable name represents the value of the object, while the variable name represents the value in the parameter list
 */
public class ThisDemo {

    //Member variables
    String name;
    int age;

    //Constructors, construction methods
    public ThisDemo(){

    }

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

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

    public void test1(){
        System.out.println("test1 Executed");
//        test2(); // You can also omit this to call other methods
    }

    public void test2(String name){
        System.out.println("test2 Executed");
        this.test1();
        System.out.println(name);
        System.out.println(this.name);
    }

    public static void main(String[] args) {
        ThisDemo td = new ThisDemo("Zhang Fei",20);
//        System.out.println(td.name);
//        System.out.println(td.age);
//        td.test1();
        td.test2("Zhao Yun");
    }
}

2. static keywords

  1. In a class, member variables declared with static are static member variables, or class properties, class variables.
  • It is a common variable of the class, belongs to the class, is shared by all instances of the class, and is explicitly initialized when the class is loaded
  • There is only one static member variable for all objects of this class. Shared by all objects of this class
  • You can use the object. Class Properties to call. Generally, however, the term "class name. class attribute" is used
  • Place static variable in method area
  1. Statically declared method
  • Call without object (class name. method name)
  • When this method is called, references to objects are not passed to it, so non-static members are not accessible in the static method
  • Static methods cannot reference this and super keywords in any way
  1. static sample code
public class TestStatic {
	int a;
	static int width;
	static void gg(){
		System.out.println("gg");
	}
	void tt(){
		System.out.println("tt");
	}
	public static void main(String[] args){
		TestStatic hi = new TestStatic();
		TestStatic.width = 2;
		TestStatic.gg(); //gg();
		//References also provide access to static variables or methods. Generally, however, class names are used. Static member name to access.
		hi.gg();
		gg();
	}
}
  1. static keyword
  • Member variables declared with static are called static variables.
  • A method declared with static is called a static method
  • Static variables and static methods are also known as class variables and class methods
  • static Keyword Usage-Classroom demo
package netclass02;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/1/7 - 01 - 07 - 15:17
 * @Description: netclass02
 * @version: 1.0
 */
/*
 *  How many objects are there in a class using static statistics?
 */
public class StaticDemo2 {

    static int count;
//    int count;

    public StaticDemo2(){
        count++;
        System.out.println("Created" +count + "Objects");
    }

    public static void main(String[] args) {
        new StaticDemo2();//1
        new StaticDemo2();//2
        new StaticDemo2();//3
    }
}
  1. Access to static properties
  • Object name. attribute
  • Class name. attribute
  1. Static method
  • Access modifier static return value type method name (){}
  1. Access Form
  • Object name. Method name ()
  • Class name. Method name ()
  1. Common Error 1
public void showInfo(){
	System.out.println("Full name:"+this.name+"\t Age:"+this.age+"\t City:"+this.country);
}
public static void welcome(){
	this.showInfo();//Call non-static methods of this class
	System.out.println("Welcome to Tengxun Interconnected Learning......");
}
  1. Common Error 2
  • Please point out the error in the following code
class Dog {
	private String name = "Prosperous Money"; // Nickname?
	private int health = 100; // Health Value
	private int love = 0;
	public void play(int n) {
		static int localv=5;//static variables cannot be defined in methods
		health = health - n;
		System.out.println(name+" "+localv+" "+health+" "+love);
	}
	public static void main(String[] args) {
		Dog d=new Dog();
		d.play(5);
	}
}
  1. Summary
  • The Difference between static Modification and Non-static Modification
static, non-private ly modifiedNon-static, private Modification
attributeClass Properties, Class VariablesInstance properties, instance variables
MethodClass methodInstance Method
Call MethodClass name. Attribute class name. Method () object. Property object. Method ()Object. Property object. Method ()
ascriptionclassSingle object

11. Classroom demo

package netclass02;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/1/7 - 01 - 07 - 14:46
 * @Description: netclass02
 * @version: 1.0
 */

/*
 * static:
 *       When modifying a member variable, it represents a static member variable or a class variable
 *            Common variables must be called by object name when they are used
 *            Class variable or static variable can be called either by object name or by class name
 *       When modifying a method, it represents a static method or a class method
 *            Common methods must be called by object name when used
 *            Class or static methods can use class names or object names
 *       Be careful:
 *           1,A static variable that is initialized before an object is created or, in other words, before a class is loaded
 *           2,Static variables are shared by all objects and are public variables. Objects and classes can be called directly, but it is recommended that classes be used to call them
 *           3,Member variables are in the heap, and static variables are in the static zone of the method zone
 *           4,Static variables cannot be defined in static methods
 *           5,Static methods can be called in nonstatic methods
 *           6,Non-static methods cannot be called directly in static methods; in other words, non-static methods can be called indirectly
 *           7,this call is not allowed in static methods
 *           8,A method in a generic tool class is defined as static
 */
public class StaticDemo {

    //Member variables
    String name = "zhangfei";
    static int age = 20;  //Static member variable

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

    public void test1(){
        System.out.println("test1 is a non-static method");
//        static int a = 10;
//        test2();
    }

    public static void test2(){
//        this.test1();
        System.out.println("test2 is a static method");
//        static int a = 10;
//        test1();
        new StaticDemo().test1(); //Indirect Call
    }

    public static void main(String[] args) {
        StaticDemo sd = new StaticDemo();
        System.out.println(sd.name);
        System.out.println(sd.age);

//        sd.age = 30;
//        System.out.println(sd.age);//30
//        System.out.println(sd.age);//30
//
//        sd.age = 40;
//        System.out.println(sd.age);//40
//        System.out.println(StaticDemo.age);//40
        StaticDemo staticDemo = new StaticDemo();
        staticDemo.test1();
//        StaticDemo.test2();
//        staticDemo.test2();

//        StaticDemo sd2 =new StaticDemo();
//        System.out.println(sd2.name);
    }
}

3. Code Block

  1. Concept: A piece of code enclosed in "{}"
  2. Classification: Classifiable by location
  • Normal Code Blocks - >Code blocks defined directly in methods or statements
  • Construct Code Blocks - > Code Blocks Written Directly in Classes
  • static Code Blocks - > Code Blocks Declared with static
  • Synchronize Code Blocks --> Learn when multithreaded
  1. Static Initialization Block
  • If you want some initialization of the entire class after loading, you can use the static initialization block.
  • Execute the static code block when the class is first loaded; When a class is loaded more than once, the static code block executes only once; Static is often used
    Initialize the static variable.
  • Executes when a class is initialized, not when an object is created.
  • Non-static members cannot be accessed in a static initialization block.
  • demo
public class TestStaticBlock {
	static {
		System.out.println("Here, the initialization of the executable class is performed!");
	}
	public static void main(String[] args) {
		System.out.println("main First sentence in method");
	}
}

4. demo in class

package netclass02;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/1/7 - 01 - 07 - 15:34
 * @Description: netclass02
 * @version: 1.0
 */

/*
 * Code block: A piece of code enclosed in {} is called a code block
 * Classification:
 *   Normal Code Block: Code defined in a method that is enclosed in {} is called Normal Code Block
 *   Construct Code Blocks: Code defined in classes enclosed in {} is called construct code blocks
 *           Note: Each time the code runs, the code in the construction block is added to the front of the construction method
 *                   The code in the construction block is added to each construction method, not when this (parameter) is used
 *   Static code block: Code enclosed in static {} is called static code block and executes first when the program loads
 *           Other code that needs to be prepared in advance, such as a database connection, is placed in the static block of code
 *   Synchronize code blocks:
 *           Used when using multithreading to lock space (later)
 *   Execution Order: Static Code Block--"Construct Code Block (used when creating objects)--" Common Code Block
 */
public class CodeBlockDemo {

    int x;
    int y;

    {
        System.out.println("Construct Code Block");
    }

    static{
        System.out.println("static code block");
//        x = 100;
    }

    public CodeBlockDemo(){

    }
    public CodeBlockDemo(int x){
        System.out.println("CodeBlockDemo(int x)Executed");
        this.x = x;
    }
    public CodeBlockDemo(int x,int y){
        this(x);
        System.out.println("CodeBlockDemo(int x,int y)Executed");
//        this.x = x;
        this.y = y;
    }
    public void test1(){
        System.out.println("test1 Method is executed");
        {
            System.out.println("test1 Common code blocks in methods");
        }
    }

    public synchronized void test2(){
    //Define a block of synchronized code (see you first, let's talk more about multithreading.)
//        synchronized(this){
//
//        }
    }

    public static void main(String[] args) {
        CodeBlockDemo cbd = new CodeBlockDemo();
        cbd.test1();
        {
            System.out.println("main Common code blocks in methods");
        }
        CodeBlockDemo cbd2 = new CodeBlockDemo(1,2);
    }
}

IV. package

  1. Why do I need a package?
  • To solve the problem of duplicate names between classes.
  • For ease of management of classes: the appropriate classes are in the appropriate package
  1. How do package s work?
  • Usually the first non-commentary statement of a class.
  • Package name: Write the domain name upside down, plus the module name, and do not manage the class internally.
  1. Matters needing attention:
  • Write items with packages instead of default packages.
  • com.tensent and com.tensent.oa, these two packages have no containment relationship and are completely separate packages. Just look logically
    The latter is part of the former.
  1. The main components of JDK
  • java.lang
    Contains core classes of the Java language, such as String, Math, Integer, System, and Thread, which provide common functionality.
  • java.awt
    Contains classes that make up the abstract window toolkits used to build and manage the graphical user interface (GUI) of applications.
  • java.net
    Contains classes that perform operations that are not network related.
  • java.io
    Contains classes that provide a variety of input/output functions.
  • java.util
    Contains utility classes such as defining system attributes and using functions related to dateless calendars.
    5. demo in class
package netclass02;

import java.util.Date;
import java.util.Scanner;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/1/7 - 01 - 07 - 16:24
 * @Description: netclass02
 * @version: 1.0
 */

/*
 * package:Package, which corresponds to the file system as a multilevel directory
 *   To solve two problems:
 *       1,File Name Issue
 *       2,For the convenience of managing classes, place code for specific processing functions in the same directory
 *   Use:
 *       The generic definition package is placed on the first line of the java file
 *           package Reverse Domain Name
 *              Examples: www.taobao.com
 *              Package name: com.taobao.
 *           package com.tensent.entry name
 *         Naming rules for package names:
 *                 Enterprise nature. Business name. Project name. Module name. Submodule name...
 *                      Enterprise nature: com org edu gov
 *                      Business name: Alibaba Baidu Huawei tensent
 *                      Project name: OA ERP HRMS CRM
 *                      Module name: ums--userManagementSystem User Management System
 *                               oms--orderManagementSystem  Order Management System
 *                               pms--productManagementSystem Product Management System
 *           Full package name: com.alibaba.taobao.ums/com.alibaba.taobao.oms
 *   Fully qualified name: package name + class name
 *
 *   JDK Common packages:
 *       lang: No need to import manually, load automatically
 *       awt:  Includes some common GUI GUI classes (this is no longer needed, just learn about it)
 *       util: Tool kit
 *       net: Network Packet
 *       io: Input Output Stream Packet
 *
 */
public class PackageDemo {

    public static void main(String[] args) {
//        java.util.Date date = new java.util.Date();
//        java.util.Scanner scanner = new java.util.Scanner(System.in);

        Date date = new Date();
        Scanner scanner = new Scanner(System.in);

//        System.out.println(Math.random());
//        System.out.println();
    }
}

V. import

  1. Why do I need import?
    If import is not used, this is the only way we can use classes from other packages: java.util.Date, too much code to write and maintain. Import allows you to import classes under other packages so that they can be called directly from the class name in this class.
  2. How does import work?
    import java.util.Date;
    import java.util. *; // Import all classes under the package. Compilation speed is reduced, but not run speed.
  3. Points to note:
    java imports java by default. All the classes are in the Lang package, so we can use them directly.
    If two classes with the same name are imported, the calling related class can only be displayed with the package name + class name:
    java.util.Date date = new java.util.Date();
  4. import static
  • Role of static import: Static properties used to import specified classes
  • JDK5. Increase after 0!
  • How to use:
    import static java.lang.Math. *;// Import all static properties of Math class
    import static java.lang.Math.PI; // Importing PI properties of Math classes
    Then we can use it directly in the program: System.out.println(PI);
    5. demo in class
package netclass02;

import static java.lang.Math.*;
/**
 * @Auther: Yu Panpan
 * @Date: 2022/1/7 - 01 - 07 - 16:46
 * @Description: netclass02
 * @version: 1.0
 */

/*
 * import:
 *   Use the import tool when you need to introduce other java classes that are not lang packages
 *       If you do not use import, you must add the fully qualified name of a class each time you use it, which is too cumbersome
 *
 *   Usage:
 *       import java.Package name. Class name; Importing specific classes is recommended
 *       import Package name. *; Importing all class files under the current package is not recommended because it does not affect the speed of the run, but it does affect the speed of compilation.
 *   Be careful:
 *       When multiple classes with the same name are required in a java file, you can only choose to import one and the other using a fully qualified name
 *
 *   Static Guide:
 *       Static packages can be used when you need to use more than one method of a class without writing its name frequently
 */

public class ImportDemo {

    public void abs(){
    }
    
    public static void main(String[] args) {
//        Scanner scanner = new Scanner(System.in);

//        java.util.Arrays.sort(new int[]{1,3,5,4,2});

        //Using the Person class in netlclass01
//        Person person = new Person();

//        Date date = new Date();

//        long time = 12332423;
//        java.sql.Date date1 = new java.sql.Date(time);

//        System.out.println(Math.random());
//        System.out.println(Math.sqrt(4));
//        System.out.println(Math.abs(-2));

        //Static packages can omit class names
        System.out.println(random());
        System.out.println(sqrt(4));
        System.out.println(Math.abs(-10));
    }
}

6. Packaging

  1. Why use encapsulation
    What's wrong with the code below?
Dog d = new Dog();
d.health = -1000;//Property Access, Unreasonable Assignment

How to solve the above design defect? -> Use encapsulation

  1. What is encapsulation
  • One of the Three Object Oriented Features - Encapsulation
    - The concept of encapsulation
    Encapsulation: Hides certain information about a class inside the class, and does not allow direct access by external programs
    Question, but through the methods provided by this class, operations and access to hidden information are implemented
  1. Benefits of packaging
  • Hide class implementation details
  • Data can only be accessed by prescribed methods
  • Easy to add control statements
  • Easy to modify implementation
  1. Encapsulation
  • Why do I need to encapsulate? What is the function and meaning of packaging?
    I want to watch TV. Just press the switch and change stations. It's necessary to know what's inside the TV
    Structure? Is it necessary to touch the picture tube?
    I want to drive,....
    Hide the complexity inside the object and only expose simple interfaces to the outside world. Facilitate external calls to improve system
    Traditional scalability and maintainability.
  • Our program design pursues "high cohesion, low coupling".
    High cohesion means that the internal data manipulation details of a class are done by itself and external interference is not allowed.
    Low coupling: Expose only a small number of methods for external use.
  1. How to use encapsulation
  • Steps for encapsulation
  1. Summary
  • class diagram
  • demo
class Dog {
	private String name = "Prosperous Money"; // Nickname?
	private int health = 100; // Health Value
	private int love = 0; // Intimacy
	private String strain = "The Labrador Retriever"; // Varieties
	public int getHealth() {
		return health;
	}
	public void setHealth (int health) {
		if (health > 100 || health < 0) {
			this.health = 40;
			System.out.println("Health value should be between 0 and 100, default value is 40");
		}
		else{
			this.health = health;
		}
}
// Other getter/setter methods

7. demo in Classroom

package netclass02;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/1/7 - 01 - 07 - 17:13
 * @Description: netclass02
 * @version: 1.0
 */

/*
 *   When defining a class, you need to include the following components:
 *       Private Properties
 *       Construction methods (parameterless and custom construction methods)
 *       set/get Method
 *       General method
 */


public class Dog {

    private String name;
    private int age;  //Private property, can only be called in the current class
    private int weight;

    public Dog(){

    }

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

    //Define a method for setting age
    public void setAge(int age){
        if(age > 0){
            this.age = age;
        }else{
            System.out.println("The age you entered is not valid, please re-enter it!");
        }
    }

    //Define a method for getting age
    public int getAge(){
        return this.age;
    }

    public String getName() {
        return name;
    }

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

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public void eat(){
        System.out.println("eating bones");
    }

    public void play(){
        System.out.println("playing...");
    }

    public void show(){
        System.out.println("name:" +this.name);
        System.out.println("age:" +this.age);
        System.out.println("weight:" +this.weight);
    }
}

Test Class

package netclass02;

/**
 * @Auther: Yu Panpan
 * @Date: 2022/1/7 - 01 - 07 - 17:14
 * @Description: com.tensent.test
 * @version: 1.0
 */

/*
 * Packaging:
 *       Concepts:
 *           Hide some information of the class inside the class and do not allow direct access by external programs.
 *           Instead, it provides methods for manipulating and accessing hidden information
 *       What does packaging solve?
 *          If any of the processing classes can assign Dog directly, unexpected results can occur when the values are inaccurate.
 *           How do I add some logic to the assignment?
 *               Encapsulation can solve this problem
 *       Effect:
 *           Encapsulation guarantees the specification of the data, and data that does not conform to the specification will not be operational
 *       Benefits:
 *           1,Hide class internal implementation details
 *           2,Can only be accessed by the provided method, other methods cannot be accessed
 *           3,Complex logical judgment statements can be added to suit your needs
 *           4,Easy to modify implementation
 *       Object-oriented encapsulation (narrow sense) can be summarized in one sentence: to ensure data security and specifications
 *           Setting attributes in a class as private provides a public external method for the program to invoke, enabling rich detail
 *       Generalized encapsulation:
 *           Code blocks that accomplish specific functions can be encapsulated into a method that can be invoked by different programs
 */
public class DogTest {

    public static void main(String[] args) {
        Dog dog = new Dog();
//        dog.name= "wangwang";
//        dog.age = -10;
//        dog.setAge(20);
//        dog.weight = 35;
//        dog.show();
        dog.setName("wangwang");
        dog.setAge(20);
        dog.setWeight(35);
        System.out.println(dog.getName());
        System.out.println(dog.getAge());
        System.out.println(dog.getWeight());
    }
}

7. Three Object-Oriented Features

  1. inheritance (later)
  • Subclass parent
  • Subclasses can inherit properties and methods from their parent
  • Subclasses can provide their own separate properties and methods
  1. Encapsulate/Hide encapsulation
  • Hide some properties and methods from the outside
  • Exposing certain properties and methods to the public
  1. polymorphism (later)
  • To accommodate a variety of changes in requirements, make your code more generic!
  1. Procedure-oriented has only encapsulation (function encapsulation, not data encapsulation), no inheritance, and no polymorphism

8. Encapsulate by using access controller (next lecture)

To be continued...

9. Summary (next lecture)

To be continued...

10. Homework (next lecture)

1. Exercise 1 - Design Dog and Enguin Classes

  • Requirement Description:
    - Use object-oriented thinking to abstract Dog and Penguin classes and draw corresponding class diagrams
typeattributeattributeattributeattributebehavior
DogNickname?Health ValueIntimacyVarietiesOutput Information
penguinNickname?Health ValueIntimacyGenderOutput Information

- Write Dog and Penguin classes from class diagrams
- Add a default construction method

2. Exercise 2 - Printing Dog Information 2-1

  • Requirement Description:
    - Choose to adopt a pet (dog) based on console prompts,
    ▪ Enter nickname, variety, health value
    ▪ Print pet information
    - To ensure the validity of health values (between 1 and 100)

3. Exercise on Computer 3 - Construction Method with Parameters for Dog Class

  • Requirement Description:
    - Add a parametric construction method
Dog(String name, String strain)

- Modify the Test class to create objects using a parameterized construction method

4. Exercise 4 - Manipulating the Sex Attributes of Penguins

  • Requirement Description:
    - Provide SEX_to Penguin class MALE and SEX_ Two static constants of FEMALE, one for "Q Zi" or the other for "Q Zi"
    - Modify the Test class to assign gender using static constants
    - Modifying the penguin's sex can only take the value male or female, which is achieved by modifying the static variable

Keywords: Java Back-end OOP JavaSE

Added by MarkR on Fri, 07 Jan 2022 19:03:01 +0200