Java类this关键字与static关键字

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java类this关键字与static关键字

三天晒网且从不打鱼   2022-09-29 我要评论

前言

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

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);
    }
}

输出结果:

static关键字用法:

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

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

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

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们