Being imprisoned for 100,000 years, java is crazy

8.1Java class package
Every time a class is defined in Java, after being compiled by the Java compiler, a file with the extension .class will be generated. When the scale of the program gradually expands, it is easy to cause name conflicts. Thousands of classes with various functions are provided in the JDK API, and Java provides a mechanism for managing files, which is the class package.

8.1.1 Class name conflict
Each interface or class in Java comes from a different class package. Whether it is a class and interface in Java API or a custom class and interface, it needs to belong to a certain class package, which contains some classes and interfaces. Without the existence of packages, managing class names in programs would be a real hassle. If the program consists of only one class, the problem of overlapping class names will naturally not occur, but as the number of classes in the program increases, this problem will inevitably occur. For example, if you define a login class in the program, you need to define a class named login because of business needs, but the functions implemented by these two classes are completely different, so the problem arises-the compiler will not allow the existence of the same name. document. The solution to this type of problem is to place the two classes in different class packages.

8.1.2 Complete classpath
The String class is often used to write Java programs. In fact, the String class is not its full name. Its full name is: java.lang.String, java.lang is the name of the package, and String is the name of the class. A complete class name requires the combination of the package name and the class name. Each class belongs to a class package. As long as the classes in the same class package have different names, conflicts between classes with the same name can be effectively avoided.
For example, if the java.util.Date class and the java.sql.Date class are used in a program at the same time, if the complete class path is not specified in the program, the compiler will not know that this code uses the java.util class package. The Date class is still the Date class in the java.sql class package, so you need to give the complete class path in the specified code.
For example, to use the full path of two different Data classes in a program, you can use the following code:

java.util.Date date=new java.uitl.Date();
java.sql.Date date2=new java.sql.Date(1000);

It is very important to adopt the class package mechanism in java. The class package can not only solve the problem of class name conflicts, but also help developers manage huge application components and facilitate software reuse when developing huge applications.

8.1.3 Create package
The steps to create a package in Eclipse are as follows:
(1) Right-click on the src node of the project and select the “New”/”Package” command (NEW/package in English).
(2) The “NEW Java Package” dialog box pops up, enter the new package name in the “Name” text box, such as com.mr, and click the “Finish” button.
(3) When creating a class in Eclipse, you can right-click on the newly created package and select the “New” (NEW) command, so that the newly created class will be saved in the package by default.
In Java, the package name design should correspond to the file system structure, such as a package named com.mr, then the classes in the package are located in the mr subfolder under the com file, and the classes that do not define the package will be summarized in the default package (default package). In actual development, package names should be set for all classes, which is a good programming practice. The syntax for defining a package name in a class is as follows:

package package name

When specifying a package name in a class, the package expression needs to be placed on the first line of the program, which must be the first line of non-comment code in the file. After using the package keyword to specify the package name for the class, the package name will be part of the class name, indicating that the full name of the class must be specified. For example, when using the Dog.java class located in the com.mr package, you need to use an expression of the form com.mr.Dog.
Note: Java package naming rules use all lowercase letters.
In Section 8.1.1, we have talked about the conflict of class names. Some readers may have doubts, so many packages will not cause package name conflicts? It is possible. In order to avoid such problems, defining the package name in Java usually uses the reverse order of the creator’s Internet domain name. Since the Internet domain name is unique, the package name will naturally not conflict. Let’s look at an example.

[Example 8.1] Create a custom Math class
Create a Math class in the project, specify the package name as com.mr in the class creation dialog box, and output in the main method that this class is not the Math class in the java.lang package (the java. lang.Math class)

package com.mr;//Specify the package name
 
public class Math {
 
 public static void main(String[] args) {
 System.out.println("Not java.lang.Math class, but com.mr.Math class");
 }
 
}

Running result:

In this example, the package name is specified in the first line of the program, and the Math class is defined in the com.mr package. The java.lang.Math class is provided in the Java class package, and this example defines the com.mr.Math class. It can be seen that there is no problem in defining the same class name in different packages, so using packages in Java can effectively manage Classes for various functions.

8.1.4 Import package
1. Use the import keyword to import the package
If the Math class needs to be used in a certain class, how to tell the compiler which package the Math class should currently use is java.lang.Math class i or com.mr.Marh class? This is a nagging question. At this point, you can use the import keyword in java to specify. For example, if the import keyword is used to import the com.mr.Math class in the program, the com.mr.Math class will be automatically selected when the Math class is used in the program. The syntax of the import keyword is as follows:

import com.mr.*;//Import all classes in com.mr package
import com.mr.Math//Import the Math class in the com.mr package

When using the import keyword, you can specify a complete description of the class of the class. If you want to use more classes in the package, you can add * after the package specification when using the import keyword, which means that you can use this in the program All classes in the package.
Note: If the com.mr.Math class has been imported in the class definition, the complete class name with the package format must be specified when using the Math class in other packages in the class body. For example, when using the Math class of the java.lang package under the above circumstances, the full name format java.lang.Math must be used.
When the import keyword is added to the program, it starts to search in the directory specified by CLASSPATH, searches for the subdirectory com.mr, and then searches for the name matching from the compiled files in this directory, and finally finds Math.class document. In addition, when using import to formulate all the classes in a package, the classes in the sub-packages of this package will not be specified. If the classes in the sub-packages of this package are used, the sub-packages need to be referenced separately again.
2. Use import to import static members

[Example 8.2] Use Import to import static members
Create an importTest class in the project, and use the import keyword to import static members in this class.

package com.mr;
import static java.lang.Math.max;
import static java.lang.System.out;
 
public class ImportTest {
 
 public static void main(String[]args) {
  
 
  out.println("The larger value of 1 and 4 is" + max(1,4));
 }
}

Running result:

It can be seen from this example that the static member method max() in the java.lang.Math class and the out member variable in the java.lang.System class are respectively imported using import static, and these can be directly referenced in the program Static members such as direct use of out.println () expression and max () method in the main method.

8.2 Internal classes
In the previous learning process, if two classes are defined in one file, neither class is inside the other class. If another class is defined in the class, the class defined in the class is called an inner class. Member inner classes and anonymous classes are the most common inner classes.

8.2.1 Inner classes of members
1. Introduction to member inner class
Using an inner class in a class, you can directly access the private member variables of the class in the inner class. The syntax for member inner classes is as follows:

class OuterClass{//outer class
class InnerClass{//inner class
}
}

Member methods and member variables of the outer class can be freely used in the member inner class, although these class members are modified as private.

[Example 8.3] Simulate engine ignition using member internal class

public class Car {//Create a car class
 private String brand;//Car brand
 public Car(String brand) {//The construction method of the car class, the parameter is the car brand
  this.brand=brand;//Assign the car brand
 }
 class Engine{//Engine class (internal class)
  String model;//engine model
   public Engine(String model) {//The construction method of the engine class, the parameter is the engine model
    this.model=model;//Assign a value to the engine
   }
   public void ignite() {//(engine) ignition method
    System.out.println("engine" + this.model + "ignition");
   }
   }
   public void start() {//Start the car method
    System.out.println("start" + this.brand);
   }
 public static void main(String[] args) {
  Car car=new Car("Volkswagen Langxing");//Create a car class object and assign a value to the car brand
  car.start();//The car class object calls the start (car) method
  //
  Car.Engine engine=car.new Engine("EA211");
  engine.ignite();
  }
}

Running result:

Members of inner classes can be used not only in outer classes, but also in other classes. The syntax for creating inner class objects inside other classes is very special, the syntax is as follows:

Outer class outer=new outer class();
Outer class. Inner class inner=outer.new inner class();

Notice
(1) If the inner class object is instantiated outside the outer class and non-static method, the type of the object needs to be specified in the form of “outer class. inner class”.
(2) The internal class object will depend on the external class object. Unless there is already an external class object, the internal class object will not appear in the class.
2. Use the this keyword to get the reference of the inner class to the outer class
If the member variable defined in the outer class has the same name as the member variable of the inner class, you can use the this keyword.

[Example 8.4] Calling an object of an outer class in an inner class

public class TheSameName {
 private int x=7;//x of the external class
 private class Inner{
  private int x=9;//x of inner class
  public void doit() {
   int x=11;//local variable x
   x + + ;
   this.x ++ ;//call x of the inner class
   TheSameName.this.x++;//Call x of the external class
  }
 }
 
}

In a class, if you encounter the same member variable name of the inner class and the outer class, you can use the this keyword to handle it. For example, using the this.x statement in the inner class can call the member variable x of the inner class, and using TheSameName.this.x statement can call the member variable x of the outer class, that is, use the outer class name followed by a dot operator and The this keyword can be used to obtain a reference to the external class.

8.2.2 Anonymous inner class
An anonymous class is just a way of writing the class body when creating an object. Anonymous classes are characterized by “use and write now”, and their syntax is as follows:

new parent class/parent interface(){
What the subclass implements
};

[Example 8.5]

abstract class Dog{
 String color;
 public abstract void move();
 public abstract void call();
}
 
public class Demo {
 
 public static void main(String[] args) {
  Dog maomao=new Dog() {//Anonymous inner class
   public void move() {
    System.out.println("running on four legs");
   }
   public void call() {
    System.out.println("呵呵~");
   }
   
  };
maomao.color="Grey";
maomao. move();
maomao. call();
 }
 
}

Running result:

The use of anonymous classes should follow the following principles:
Anonymous classes cannot write constructors
Anonymous classes cannot define static members
If the object created by the anonymous class is not assigned to any reference variable, it will cause the object to be destroyed by Java once it is used up.