Study notes: java this and static

Keyword this

In Java, this keyword is more difficult to understand, and its function is very close to its meaning.
It is used inside the method, that is, a reference to the object to which this method belongs;
it is used inside the constructor to indicate the object being initialized by the constructor.
This represents the current object. You can call the properties, methods, and constructors of the class
.
When should you use the this keyword?
When the object calling the method needs to be used in the method, use this

class Person{
    
    		// 定义Person类
    private String name ;
    private int age ;
    public Person(String name,int age){
    
    
        this.name = name ;
        this.age = age ;  }
    public void getInfo(){
    
    
        System.out.println("姓名:" + name) ;
        this.speak();
    }
    public void speak(){
    
    
        System.out.println(“年龄:” + this.age);
    }
}

Keyword static

Range of use:
In Java classes, static can be used to modify attributes, methods, code blocks, and internal classes

    被修饰后的成员具备以下特点:
    随着类的加载而加载
    优先于对象存在
    修饰的成员,被所有对象所共享
    访问权限允许时,可不创建对象,直接被类调用
class Circle{
    
    
    private double radius;
    public Circle(double radius){
    
    this.radius=radius;}
    public double findArea(){
    
    return Math.PI*radius*radius;}}

Create two Circle objects

Circle c1=new Circle(2.0);	//c1.radius=2.0
Circle c2=new Circle(3.0);	//c2.radius=3.0

The variable radius in the Circle class is an instance variable, which belongs to each object of the class and cannot be shared by different objects of the same class.
In the above example, the radius of c1 is independent of the radius of c2 and is stored in a different space. The radius change in c1 will not affect the radius of c2, and vice versa.
The design idea of ​​class attribute and class method

Guess you like

Origin blog.csdn.net/qq_44909275/article/details/105122328