Chapter 3 Basics of Classes
3.1 Basic concepts of classes
One way to understand a class is a container of functions. For example, in the class Math of the Java API, in the class Math, the methods we can reference are public static
modified.
static
Represents a class method , also called a static method . The opposite of class methods is instance methods . Instance methods are not static
decorated and must be called through instances or objects, while class methods can be called directly through the class name without creating an instance.
public
The method is public and can be called externally from anywhere.
private
Indicates that the method is private, this method can only be called by other functions in the same class, and cannot be called by external classes.
It is a basic way of thinking for computer programs to avoid misoperation through private encapsulation and hiding of internal implementation details.
The following are the commonly used methods of the Math class .
method | Features |
---|---|
int round(float a) | |
double sqrt(double a) | |
double ceil(double a) | Improvement arrangement |
double floor(double a) | Round down |
double pow(double a, double b) | |
int abs(int a) | |
int max(int a, int b) | |
double log(double a) | Take the natural logarithm |
double random() | Produces a (0, 1) (0, 1)(0,1 ) Random number in the range |
The following is a common method of class Arrays related to the operation of arrays .
method | Features |
---|---|
void sort(int[] a) | Sort ascending |
void sort(double[] a) | |
int binarySearch(long[] a, long key) | Find the position of key in array a |
void fill(int[] a, int val) | Assign the same value to all elements of the array |
int[] copyOf(int[] originnal, int newLength) | Array copy |
boolean equals(char[] a1, char[] a2) | Determine whether the two arrays are the same |
The class is actually a custom data type. A type is mainly composed of 4 parts.
- The attributes of the type itself are reflected by class variables (static modification, also known as static variables or static member variables).
- The operations that the type itself can perform are reflected by class methods (static modification, also known as static methods or static member methods).
- The attributes of a type instance are reflected in instance variables (no static modification, also called member variables).
- The operations that a type instance can perform are reflected in instance methods (no static modification, also called member methods).
We can use final
to represent constants.
In the definition of a class, the class cannot be used private
to modify, but it can be without modifiers, which means a kind of package visibility . But when defining inner classes, you can use private
modifiers.
Similar to class variables, instance variables also have public
and private
modifiers, and they cannot be static
modified.
The difference between instance method and class method is as follows.
- Class methods can only access class variables, not instance variables, and can call other class methods, but cannot call instance methods of this class.
- Instance methods can access both instance variables and class variables. You can call both class methods and instance methods.
The usage process of the class is basically as follows.
public class ChapterThree {
public static void main(String[] args) {
Point p = new Point();
p.x = 2;
p.y = 3;
System.out.println(p.distance());
}
}
Among them, the creation statement of the instance of the class or the object is Point p = new Point();
. Among them, it new Point();
is necessary. In C++, Point p
you can create an instance or object of a class. But in Java, Point p
only a variable that can refer to an instance or object is created, that is p
, the value is the actual storage address of the object or instance. At this time, new Point()
memory is allocated for the instance of the object, and the assignment statement assigns the starting address of the memory where the object is stored p
, so that p
this instance can be referenced.
When creating an instance of an object, all instance variables are assigned a default value. Among them, the default value of numeric type variables is 0, boolean is false, char is "\u0000", and reference type variables are null. Null is a special value, which means that this reference type variable does not point to any object.
Unlike C++, Java can specify the initial value when defining a member variable, regardless of whether the member variable is static final
.
The construction method in Java can this(...)
be called through .
Each class has at least one constructor, new
which will be called during the process of creating an object. If the defined constructor is not displayed, the Java compiler will automatically generate a default constructor . But after displaying the definition of the constructor, the Java compiler no longer generates the default constructor.
The construction method can be used private
to modify.
The life cycle of classes and objects is as follows.
- When the program creates an object of a class through new for the first time, or directly accesses class variables and class methods through the class name, Java loads the class into memory and allocates a space for this class. This space includes class definitions, member variables, and member methods.
- After the class is loaded into memory, it is generally not released until the end of the program.
- Each time you do a new operation, an area is divided in the memory to store the object, and each area corresponds to an independent instance variable.
- The release of objects is managed by Java's automatic garbage collection mechanism. When there is no active variable referencing the object, the space corresponding to the object may be released.
Objects, like arrays, have two pieces of memory. The part that stores the address is allocated on the stack, and the part that stores the actual content is allocated on the heap.
3.2 Combination of classes
The combination of classes is actually the use of objects of another class in the class. For example, String
and Date
class.
Each class encapsulates its internal details, provides high-level functions to the outside, and enables other classes to consider and solve problems at a higher level. This is a basic way of thinking in program design.
3.3 Code organization mechanism
A package is similar to a folder, and classes and interfaces are placed in the package. The package name is .
divided by, for example java.lang.String
, the fully qualified name of the class with the complete package name . All classes and interfaces in the Java API are located under the package Java or javax. Java is a standard package and javax is an extended package.
When defining a class, keywords should be used package
to declare the package name, for example.
package shuo.laoma;
public class Hello{
}
The package declaration statement should be at the top of the source code, and there can be no statements other than comments in the front.
Note that the package name and file directory must match. If the root directory where the source file is stored is E:\src
, Hello
the file where the above class is located is Hello.java
, and its full path should be E:\src\shuo\laoma\Hello.java
. If it does not match, Java will prompt a compilation error.
The purpose of the package is to avoid naming conflicts and facilitate code organization.
Mutual references between classes in the same package do not require package names and can be used directly. If the class is not in the same package, you must know which package it is in. At this time, there are two solutions, one is to use the fully qualified name of the class, and the other is to introduce the used class into the current class. In particular, the java.lang
package can be used directly in the class, the need to introduce, does not require the fully qualified name, e.g. String
, System
.
import
A class can be introduced into the file of the current class by keywords, for example.
package shuo.laoma;
import java.util.Arrays;
public class Hello{
}
When doing import
this, you can *
import all the classes under a package at once, for example
import java.util.*;
But this introduction cannot be recursive.
In a class, references to other classes must be uniquely determined, and there can be no classes with the same name. If there are classes with the same name, you can only import
import one of them, and other classes with the same name need to be accessed through the fully qualified name.
import
The statement should be placed package
after, before the definition of the class.
There is a special type of import called static import , which has a static
keyword that can directly import public static methods or members of the class. However, static imports should not be overused, otherwise it is difficult to distinguish which type of code is being accessed.
We can pack the compiled code into a file, which is convenient for other programs to call.
In Java, the compiled Java class of one or more packages can be packaged into a file. The command is jar
, the packaged file extension is .jar
generally called a jar package .
Java class libraries and third-party class libraries are provided in the form of jar packages, which classpath
can be used by adding them to the class path .
From the Java source code to the running program, two steps are required: compilation and linking. Compilation is to use javac
commands to compile the source code file to .class
the bytecode with the extension . When linking, use java
commands to parse the .class
file, convert it into a binary code that can be recognized by the machine, and then run it on the Java virtual machine.
Parameter specifies the need to compile a classpath Java runtime classpath . There can be multiple class paths. For direct class files, the path is the root directory of the class file. For jar packages, the path is the full name of the jar package.
When the Java source code is compiled, the Java compiler will determine the fully qualified name of each referenced class, based on the import
statement sum classpath
. When Java is running, it will find and load the class according to the fully qualified name of the class determined at compile time. The way to find it is to find it in the classpath.