java classes and objects 2

1. Java instance variables and class variables

Definition of instance variables and class variables

When declaring member variables, those modified with the keyword static are called class variables, class variables are also called static variables or static variables, and those not modified with the keyword static are called instance variables.

class Main {
    
    
    float x; //实例变量
    static int y; //类变量
}

Notice:

The keyword static needs to be placed before the type of the variable.

The difference between instance variables and class variables

  1. The instance variables of different objects are different from each other:
    a class can create multiple different objects by using the new operator, and these objects will be assigned different member variables, and the instance variables assigned to different objects occupy different memory spaces. Instance variables of one object do not affect instance variables of other objects.

  2. All objects share class variables:

If there are class variables in the class, when using the new operator to create multiple different objects, the class variables allocated to these objects occupy the same memory, and changing the class variable of one object will affect the class of other objects Variables, that is to say objects share class variables.

  1. Access class variables directly by class name:

When a Java program is executed, the bytecode file of the class is loaded into memory. If the class does not create an object, the instance variables in the class will not be allocated memory. However, the class variables in the class are allocated the corresponding memory space when the class is loaded into the memory. If this class creates objects, the instance variables of different objects are different from each other, that is, different memory spaces are allocated, and class variables no longer reallocate memory. All objects share class variables, that is, the class variables of all objects are the same In the memory space, the memory space of the class variable is not released until the program exits and runs.

Therefore, class variables can be accessed not only through a certain object, but also directly through the class name, while instance variables of an object can be accessed through the object, but not using the class name.

Two, Java instance method and class method

Definition of instance methods and class methods

In the method declaration, if the method type is not modified by the keyword static, it is an instance method , and if the keyword static is modified, it is a class method, also known as a static method .

For example:

class Main {
    
    
    int a;
    float max(float b,float c) {
    
     //实例方法
        ……
    }
    static float max(float d,float e) {
    
     //类方法
        ……
    }
}

The difference between instance methods and class methods

  1. Object calls instance methods:

When the bytecode file of the class is loaded into memory, the instance method of the class will not be assigned an entry address. Only after the class creates an object, the instance method in the class will be assigned an entry address, so that the instance method can be used by any class created Object calls execute.

Notice:

When we create the first object, the instance method in the class is assigned the entry address. When the object is created again, the entry address is no longer assigned. That is to say, the entry address of the method is shared by all objects. When all objects When neither exists, the entry address of the method is canceled.

Not only instance variables can be manipulated in instance methods, but also class variables can be manipulated. When an object calls an instance method, the instance variables and class variables appearing in the method are all variables assigned to the object, but the class variables are shared with all other objects.

  1. The class name calls the class method:

For the class method in the class, when the class is loaded into the memory, the corresponding entry address is allocated, so that the class method can not only be called and executed by any object created by the class, but also can be called directly through the class name. The entry address of the class method is not canceled until the program exits.

Notice:

Instance methods cannot be called by the class name, only by the object. And because instance member variables have not allocated memory before the class creates an object, class methods cannot manipulate instance variables.

  1. Design principles of class methods:

If a method can meet the needs of the program without operating any instance variables in the class, you can consider designing such a method as a static method.

For a static method, you can call it directly with the class name without creating an object. If you create an object, it will cause the instance variables in the class to be assigned

3. Java method overloading

There are two types of polymorphism in Java: Overload and Override. Method overloading is one of the two types of polymorphism.

For example: When you ask a person to perform the "find area" operation, he may ask you what area to ask for?

Functional polymorphism means that different messages can be passed to functions, so that objects can generate corresponding behaviors according to corresponding messages. The behavior of the object is reflected by the method in the class, so the polymorphism of the behavior is the overloading of the method.

Grammatical rules for method overloading:

Method overloading means that there can be multiple methods with the same name in a class, but the parameters of these methods must be different. Either the number of parameters is different, or the number of parameters is the same, but the type of a corresponding parameter in the parameter list is different.

For example:

class People {
    
    
    float hello(int a,int b) {
    
    
        return a+b;
    }
    float hello(long a,int b) {
    
    
        return a-b;
    }
    double hello(double a,int b) {
    
    
        return a*b;
    }
}
public class Main {
    
    
    public static void main(String args[]) {
    
    
        People tom = new People();
        System.out.println(tom.hello(10,10));
        System.out.println(tom.hello(10L,10));
        System.out.println(tom.hello(10.0,10));
    }
}

insert image description hereNotice:

If two methods have the same name, the parameters must be different even if the return types are different.

4. The Java this keyword

this is a keyword in Java that represents an object. this can appear in instance methods and constructors, but not in class methods .

Use this in the constructor

When the this keyword appears in the constructor of a class, it represents the object created using the constructor.

public class People {
    
    
    int leg,hand;
    String name;
    People(String s) {
    
    
        name = s;
        this.init(); //可以省略this.,即写成init();
    }
    void init() {
    
    
        leg = 2;
        hand = 2;
        System.out.println(name+"有"+hand+"只手"+1eg+"条腿");
    }
    public static void main(String args[]) {
    
    
        People boshi = new People("布什");
    }
}

Using this in instance methods

Instance methods can only be called through the object, not through the class name. When the this keyword appears in an instance method, it represents the current object that is calling the method.

The instance method can operate the member variables of the class. When the instance member variable appears in the instance method, the general format is:

this.成员变量;

When static member variables appear in instance methods, the general format is:

类名.成员变量;
class A {
    
    
    int x;
    static int y;
    void a() {
    
    
        this.x = 10;
        A.y = 20;
    }
}

This appears in the instance method a of the class A, and this represents the current object using a , so "this.x" represents the variable x of the current object. When the object calls method a, 10 is assigned to the variable of the object x. When an object calls a method, the instance member variable in the method refers to the instance member variable assigned to the object, and the static variable is shared with other objects. Therefore, under normal circumstances, you can omit the "this." in front of the instance member variable name and the "class name." in front of the static variable.

class A {
    
    
    int x;
    static int y;
    void a() {
    
    
        x = 10; //省略this.
        y = 20; //省略类名.
    }
}

Notice:

When the name of the instance member variable is the same as the name of the local variable, "this." or "class name." in front of the member variable cannot be omitted.

Instance methods of a class can call other methods of the class. The general format for calling an instance method is:

this.方法;

The general format for a class method call is:

类名.方法;
class B {
    
    
    void b() {
    
    
        this.c();
        B.d();
    }
    void c() {
    
    
        System.out.println("hi");
    }
    static void d() {
    
    
        System.out.println("ok");
    }
}

This appears in method b in class B, and this represents the current object calling method b, so this.c() in the method body of method b is the current object calling method c, that is, calling method on an object In the process of b, method c is called again. Since this logical relationship is very clear, when an instance method calls another method, "this." or "class name." in front of the method name can be omitted.

For example:

class B {
    
    
    void b() {
    
    
        c(); //省略this.
        d(); //省略类名.
    }
    void c() {
    
    
        System.out.println("hi");
    }
    static void d() {
    
    
        System.out.println("ok");
    }
}

Notice:

this cannot appear in a class method, because the class method can be called directly through the class name, and no object may yet be born at this time.

5. Java package

Package (package) is a mechanism for managing classes in the Java language. Classes with the same name may appear in different Java source files. If you want to distinguish these classes, you need to use the package name.

package statement

Declare the package statement through the keyword package. The package statement is the first statement in the Java source file, indicating that the package in which the class defined in the source file is located is the specified package name for the class declared in the source file. The general format of the package statement is:

package 包名;

If the package statement is omitted in the source program, the classes defined and named in the source file are considered to be part of the no-package name. As long as the bytecodes of these classes are stored in the same directory, they belong to the same package, but There is no package name .

The package name can be a legal identifier, or it can be composed of several identifiers plus ".", for example:

package sunrise;
package sun.com.cn;

storage directory

If a class has a package name, it cannot be stored anywhere, otherwise the virtual machine will not be able to load such a class.

If the program uses a package statement, for example:

package tom.jiafei;

Then the directory structure of the storage file must contain the following structure: ...\tom\jiafei, for example: C:\1000\tom\jiafei, and the bytecode file of the class compiled from the source file must be saved in the directory C:\1000 In \tom\jiafei, source files can be stored arbitrarily.

If the package name of the main class is tom.jiafei, then the bytecode of the main class must be stored in the ...\tom\jiafei directory, then the main class must be run in the upper directory of tom\jiafei, assuming C:\ 1000\tom\jiafei, the operation format is as follows:

C:\1000> java tom\jiafei.主类名

6. Java import statement

A class may need an object declared by another class as its own member or local variable in a method. If the two classes are in the same package, there is no problem. However, if the two classes are not in the same package, this must use the import statement.

Import classes from the class library

Use the import statement to introduce classes in the package. When writing source files, in addition to writing classes yourself, you often need to use many classes provided by Java, and these classes may be in different packages.

In order to use the classes provided by Java, you can use the import statement to introduce the classes in the package. There can be multiple import statements in a Java source program, and they must be written between the package statement (if there is a package statement) and the definition of the class in the source file. Java provides about 130 packages.

For example:

java.lang contains all basic language classes

java.io contains all input and output classes

java.util contains utility classes

java.sql contains classes for manipulating databases

java.net contains all classes that implement network functions

If you want to introduce all classes in a package, you can use the wildcard symbol asterisk (*) instead, for example:

import java.util.*; //表示引入java.util包中所有的类
import java.util.Date; //表示引入java.util包中的Date类

Import classes from custom packages

User programs can also use the import statement to introduce classes with package names in non-class libraries, for example:

import tom.jiafei.*;

In order to make their programs use the classes in the tom.jiafei package, users can specify the location of the tom.jiafei package in the classpath. Suppose the location of the tom.jiafei package is C:\1000, that is, the class named tom.jiafei The bytecode is stored in the C:\1000\tom\jiafei directory. Users can update the value of classpath, for example:

set classpath=C:\jdk1.6\jre\lib\rt.jar;.;C:\1000
/*表示可以加载C:\1000目录中的无名包类且C:\1000目录下的子孙目录可以作为包的名字来使用*/

If the user does not want to update the classpath value, the user can create a subdirectory structure corresponding to the package under the directory where the user program is located.

For example: the directory of a certain class in the user program is C:\2000, and this class wants to use the import statement to import the class in the tom.jiafei package, then according to the package name to establish the directory structure C:\2000\tom\jiafei, there is no need to go to Modify the value of classpath, because the default classpath value is:

C:\jdk1.6\jre\lib\rt.jar;.;
/*“.;”表示可以加载应用程序当前目录中的无名包类且当前目录下的子孙目录可以作为包的名字来使用*/

Seven, Java access rights

The so-called access right refers to whether the object can operate its own variables or call methods in the class through the "." operator. Access restriction modifiers include private, protected, and public, which are Java keywords used to modify member variables or methods.

Notice:

When writing a class, the instance method in the class can always operate the instance variables and class variables in the class; the class method can always operate the class variables in the class, regardless of the access limiter.

Private Variables and Private Methods

Member variables and methods decorated with the keyword private are called private variables and private methods.

class Tom {
    
    
    private float weight; //weight是private的float型变量
    private float t(float a,float b) {
    
     //方法t是私有方法
        return a+b;
    }
}

Notice:

When an object of class Tom is created in another class, the object cannot access its own private variables and call private methods in the class.

Shared Variables and Shared Methods

Member variables and methods modified with the keyword public are called public variables and public methods.

class Tom {
    
    
    public float weight; //weight是public的float型变量
    public float t(float a,float b) {
    
     //方法t是共有方法
        return a+b;
    }
}

Notice:

When an object of class Tom is created in any class, the object can access its own public variables and call the public methods in the class.

Protected member variables and protected methods

Member variables and methods decorated with the keyword protected are called protected member variables and protected methods.

class Tom {
    
    
    protected float weight; //weight是protected的float型变量
    protected float t(float a,float b) {
    
     //方法t是受保护的方法
        return a+b;
    }
}

Notice:

When an object is created with the class Tom in another class, if this class is in the same package as the Tom class, then the object can access its own protected variable and call the protected method in the class.

Friendly Variables and Friendly Methods

Member variables and methods not decorated with keywords private, public, and protected are called friendly variables and friendly methods.

class Tom {
    
    
    float weight; //weight是友好的float型变量
    float t(float a,float b) {
    
     //方法t是友好方法
        return a+b;
    }
}

Notice:

When an object is created with the class Tom in another class, if this class is in the same package as the Tom class, then the object can access its own friendly variables and call the friendly methods in the class.

When an object is created with the class Tom in another class, if this class is in the same package as the Tom class, then the object can access its own protected variable and call the protected method in the class.

8. Class encapsulation of Java basic types

Java's basic data types include: boolean, byte, short, char, int, long, float, and double. Java also provides classes related to basic data types, which realize the encapsulation of basic data types. These classes are in the java.lang package, namely: Byte, Integer, Short, Long, Float, Double, and Character classes.

Double and Float classes

The Double class and the Float class realize the class packaging of the double and float basic type data. You can use the constructor Double(double num) of the Double class to create an object of type Double; use the constructor Float(float num) of the Float class to create an object of type Float. Calling the doubleValue() method of a Double object can return the double data contained in the object; calling the floatValue() method of a Float object can return the float data contained in the object.

Byte, Short, Integer, Long classes

The construction methods of Byte, Short, Integer and Long classes are Byte(byte num), Short(short num), Integer(int num) and Long(long num) respectively. Byte, Short, Integer, and Long objects call byteValue(), shortValue(), intValue(), and longValue() methods respectively to return the basic type data contained in the object.

Character class

You can use the constructor Character(char c) of the Character class to create an object of Character type. The Character object calls the charValue() method to return the char data contained in the object. The Character class also includes some class methods, which can be called directly through the class name to classify characters.

Nine, Java jar file

When a Java application is running, it needs to load the bytes of the used classes into the memory. Therefore, there are certain requirements for the location of the bytecode file, which are generally divided into the following four situations:

insert image description hereclass with package name

Assume the package name of the following TestOne and TestTwo classes is moon.star.

insert image description here
insert image description here
insert image description hereLearn from "https://www.dotcpp.com"

Summarize

When all the disputes of external things pour into your heart, "worry", "irritability" and so on, they will not help. Only "peace" and the integration of all things in nature can relieve worries and detach yourself.

Guess you like

Origin blog.csdn.net/weixin_51884452/article/details/130666436