软件编程
位置:首页>> 软件编程>> java编程>> Java类中this关键字与static关键字的用法解析

Java类中this关键字与static关键字的用法解析

作者:三天晒网且从不打鱼  发布时间:2023-11-09 22:45:19 

标签:Java,this,static,关键字

前言

今天给大家总结介绍一下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);
   }
}

输出结果:

Java类中this关键字与static关键字的用法解析

static关键字用法:

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

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

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

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

来源:https://blog.csdn.net/qq_53130059/article/details/126714121

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com