今天给大家总结介绍一下Java类中this关键字和static关键字的用法。



文章目录

  • this关键字用法:
  • 1:修饰属性,表示调用类中的成员变量
  • 2:this修饰方法
  • 3:this表示当前对象的引用
  • static关键字用法:
  • 1:static修饰类中的属性
  • 2:static修饰方法



this关键字用法:

this.属性可以调用类中的成员变量
this.普通成员方法(对应参数)可以调用类中的普通成员方法
this()可以调用类中的构造方法


1:修饰属性,表示调用类中的成员变量

代码示例:

public class Student {

    public String name;
    public int age;
    public String school;

    public Student(String name, int age, String school) {
        this.name = name;
        this.age = age;
        this.school = school;
    }
    
}

因为程序的就近匹配原则,编译器会从调用代码处的最近位置查找有无匹配的变量或者方法,若找到直接使用最近的变量或方法。所以如果上述代码中的带参构造方法不使用this的话我们在使用该构造方法时会遇到无法赋值成功的问题。


2:this修饰方法

this可用于构造函数之间的相互调用,可以减少构造函数代码的耦合性,使代码看起来更加整洁(不写重复代码很重要)。

未使用this前:

public class Student {

    public String name;
    public int age;
    public String school;

    public Student() {
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student(String name, int age, String school) {
        this.name = name;
        this.age = age;
        this.school = school;
    }

}

使用this后:

public class Student {

    public String name;
    public int age;
    public String school;

    public Student() {
    }

    public Student(String name, int age) {
        this();
        this.name = name;
        this.age = age;
    }

    public Student(String name, int age, String school) {
        this(name,age);
        this.school = school;
    }

}

PS:
1.this调用构造方法必须放在当前构造方法的首行调用,否则会报错。
2.对构造方法的调用不能成"环”必须线性调用,否则会陷入调用死循环。


3:this表示当前对象的引用

当前是通过哪个对象调用的属性或者方法,this就指代哪一个对象。

代码示例:

public class Student {

    public String name;
    public int age;
    public String school;

    public void show(){
        System.out.println(this);
    }

    public static void main(String[] args) {
        Student stu1 = new Student();
        stu1.show();
        System.out.println(stu1);
        System.out.println("————————————");
        Student stu2 = new Student();
        stu2.show();
        System.out.println(stu2);
        System.out.println("————————————");
        Student stu3 = new Student();
        stu3.show();
        System.out.println(stu3);
    }
}

输出结果:

java中this关键字 java this关键字的用法_java中this关键字


static关键字用法:

1:static修饰类中的属性

在Java的类中,若static修饰类中属性,称之为类的静态属性/类属性,它和具体的对象无关,该类的所有对象共享这一属性。该属性存储在JVM的方法区(不同于堆区和栈区的另一个区域),类中的所有对象共享同一个方法区(类中的常量和静态变量储存在方法区中),直接使用类名称来访问静态变量,不推荐使用某个对象来访问。

只要类一定义,JVM就会为static修饰的类属性分配空间,它和类是绑定的,使用static修饰变量的好处是当我们需要修改一个值时可以更加方便,比如学生类中的学校属性,若学校改名字了,我们没有使用static修饰,那么我们就要给每个学生都修改一次,但是使用了static则只需要修改一次。

相关问题:Java方法中是否可以定义静态变量?

解答:静态变量,当类定义时和类一块加载到内存中了,而调用方法至少是在类定义之后才能调用的,先后顺序不一样,就是说还没调用方法便已经执行了方法里面的定义变量,这是不合理的。


2:static修饰方法

static修饰方法,称之为类方法/静态方法,与具体对象无关,直接通过类名称来访问,类方法只能直接使用类中的静态属性,以及类中的静态方法。

相关问题:static关键字能否修饰类?

解答:创建一个类,就是为了产生对象!static关键字与对象无关!它们是矛盾的存在。