day10_this, package, import

Posted by itsinmyhead on Sat, 19 Feb 2022 01:04:31 +0100

this keyword

What is this? This is understood as: the current object or the object currently being created.

characteristic

  • this # is a keyword in the Java language, which is stored inside the object in the heap memory of the Java virtual machine
  • this can be regarded as a variable. It is a reference. this reference saves the memory address of the current object and points to itself
  • Any java object in heap memory has a this, that is to say, creating 100 java objects corresponds to 100 this respectively.
  • this can be used to modify and call: properties, methods and constructors
  • this can be used in instance methods and construction methods. this cannot appear in methods with static.

this can call the properties and methods of the class

  • In the member method of the class: we can call the property or method of the current object by using "this. Property" or "this. Method". However, usually, we choose to omit "this.". In special cases, if the formal parameter of the method has the same name as the attribute of the class, we must explicitly use the method of "this. Variable", indicating that this variable is an attribute, not a formal parameter. When using this to access properties and methods, if it is not found in this class, it will be found from the parent class.
  • In the constructor of the class: we can use "this. Attribute" or "this. Method" to call the object attribute or method currently being created. However, usually, we choose to omit "this.". In special cases, if the formal parameter of the constructor has the same name as the attribute of the class, we must explicitly use "this. Variable" to indicate that this variable is an attribute, not a formal parameter.

Code example

/*
    this: 
        1,this Is a keyword, all lowercase.
        2,this What is it and how is it in terms of memory?
            One object, one this.
            this Is a variable, is a reference. this saves the memory address of the current object and points to itself.
            Therefore, strictly speaking, this represents the "current object"
            this The interior of an object stored in heap memory.

        3,this Can only be used in instance methods. This is who calls this instance method.
        So this represents the current object.

        4,"this."In most cases, it can be omitted.

        5,Why can't this be used in static methods??????
            this Represents the current object. The current object does not exist in the static method.
*/
public class ThisTest01{
    public static void main(String[] args){

        Customer c1 = new Customer("Zhang San");
        c1.shopping();

        Customer c2 = new Customer("Li Si");
        c2.shopping();

        Customer.doSome();
    }
}

// Customer category
class Customer{

    // attribute
    // Instance variable (must use "reference") (accessed by)
    String name;   

    //Construction method
    public Customer(){
    
    }
    public Customer(String s){
        name = s;
    }

    // Customer shopping methods
    // Example method
    public void shopping(){
        // Who is this here? This is the current object.
        // c1 calls shopping (). This is c1
        // c2 calls shopping(),this is c2
        //System.out.println(this.name + "shopping!");

        // this.  Can be omitted.
        // this.  If omitted, the name of the "current object" is accessed by default.
        System.out.println(name + "Shopping!");
    }

    // Static method
    public static void doSome(){
        // this represents the current object, while static method calls do not require an object. Contradiction.
        // Error: cannot reference non static variable this from static context
        //System.out.println(this);
    }
}


class Student{

    // How to access instance variables? You must first create a new object through "reference." To visit.
    String name = "zhangsan";

    // Static method
    public static void m1(){
        //System.out.println(name);

        // this represents the current object.
        //System.out.println(this.name);

        // Unless you do
        Student s = new Student();
        System.out.println(s.name);

    }

    //Why are set and get methods instance methods?
    public static void setName(String s){
        name = s;
    }
    public String getName(){
        return name;
    }

    // When are methods defined as instance methods and static methods?
    // If an instance variable is directly accessed in a method, the method must be an instance method.
}

this call constructor

  • In the class constructor, we can explicitly use the "this (formal parameter list)" method to call other constructors specified in this class
  • Constructor cannot call itself through "this (formal parameter list)"
  • If there are n constructors in a class, "this" is used in up to n - 1 constructors
  • Specifies that "this (formal parameter list)" must be declared on the first line of the current constructor
  • Inside the constructor, at most one "this (formal parameter list)" can be declared to call other constructors
package demo03;
/*
    1,this In addition to being used in instance methods, it can also be used in construction methods.
    2,New syntax: to call another constructor of this class through the current constructor, you can use the following syntax format:
        this(Actual parameter list);
            Code reuse can be achieved by calling construction method 2 through a construction method 1.
            However, it should be noted that "constructor 1" and "constructor 2" are in the same class.

    3,this() What is the function of this grammar?
        Code reuse.

    4,Rote memorization:
        A call to this() can only appear on the first line of the constructor.
*/
class Person{ // Define the Person class
    private String name ;
    private int age ;
    public Person(){ // Parameterless constructor
        System.out.println("New object instantiation") ;
    }
    public Person(String name){
        this(); // Call the parameterless constructor in this class
        this.name = name ;
    }
    public Person(String name,int age){
        this(name) ; // Call constructor with one parameter
        this.age = age;
    }
    public String getInfo(){
        return "full name:" + name + ",Age:" + age ;
    }
}

The process of object creation and the essence of this

Construction method is an important way to create Java objects. When calling the constructor through the new keyword, the constructor does return the object of this class, but this object is not completely created by the constructor. There are four steps to create an object:

  1. Allocate object space and initialize the object member variable to 0 or empty
  2. Perform display initialization of attribute values
  3. Execution construction method
  4. Returns the address of the object to the relevant variable

The essence of this is "the address of the created object"! Because the object has been created before the construction method call. Therefore, you can also use this to represent the "current object" in the construction method.

Keyword: package

Package statement, as the first statement in the Java source file, indicates the package of the class defined in the file. (if this statement is defaulted, it is specified as nameless package). Its format is:

  • Package top level package name Sub package name;  
package pack1.pack2; //The specified class PackageTest belongs to package Pack1 pack2
  • The package corresponds to the directory of the file system. In the package statement, use "." To indicate the hierarchy of packages (directories);
  • Packets are usually identified by lowercase words. Usually use the inversion of your company's domain name: com wrg. xxx

Function of package:

  • Packages help manage large software systems: classify classes with similar functions into the same package. For example: MVC design pattern
  • Packages can contain classes and sub packages, which are divided into project levels for easy management
  • Resolve class naming conflicts
  • Control access

Introduction to main packages in JDK

Common packages in Java

explain

java.langContains some core classes of Java language, such as String, Math, Integer, System and Thread, which provide common functions
java.netContains classes and interfaces that perform network related operations.
java.io-Contains classes that provide multiple input / output functions.
java.util-It contains some utility classes, such as defining system features, collection framework classes of interfaces, and using functions related to date and calendar.
java.textContains some java formatting related classes
java.sql-Contains java JDBC database programming related classes / interfaces
java.awtContains several classes that make up the abstract window toolkits, which are used to build and manage the graphical user interface (GUI) of the application.

matters needing attention

  • Add packages when writing projects. Do not use the default package.
  • com.gao and com gao. Car, these two packages have no relationship, and are two completely independent packages. It just seems logically that the latter is part of the former.

Keywords: import

In order to use Java classes defined in different packages, you need to import the required classes or all classes (. *) under the specified package level with an import statement. The import statement tells the compiler where to look for classes. Syntax format:

  • import package name Class name;  
import pack1.pack2.Test; //import pack1.pack2.*; Indicates the introduction of Pack1 All structures in pack2 package

be careful:

  • Use import to explicitly import the classes or interfaces under the specified package in the source file
  • The declaration is between the declaration of the package and the declaration of the class.
  • If you need to import multiple classes or interfaces, you can explicitly import multiple import statements in parallel
  • Example: Java. Can be used util.* Import all classes or interfaces under the util package at one time.
  • If the imported class or interface is Java Lang package or the current package, you can omit this import statement.
  • If you use classes with the same name under different packages in your code. Then you need to use the full class name of the class to indicate which class is called.
  • If you have imported Java Class under package a. If you need to use the classes under the sub package of package a, you still need to import them.
  • Use of import static combination: call static properties or methods under the specified class or interface
  • Static import is in jdk1 5. The newly added function is used to import the static properties and static methods of the specified class, so that we can directly use the static properties and static methods