我是 Java 编程语言的新手。
我熟悉 C 和 C++,但无法理解以下程序的行为。
public class Test {
static int x = 11;
private int y = 33;
public void method1(int x) {
Test t = new Test();
this.x = 22;
y = 44;
System.out.println("Test.x: " + Test.x);
System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
}
public static void main(String args[]) {
Test t = new Test();
t.method1(5);
}
}
正确的输出:
Test.x: 22
t.x: 22
t.y: 33
y: 44
预期输出:
Test.x: 22
t.x: 22
t.y: 44 // As variable y is modified inside the function.
y: 44
即使将行从 y = 44;
更改为 this.y = 44;
也没有给出预期的输出。
最佳答案
静态变量和非静态变量的基本区别
class Student {
private int id;
private String name;
static String collegeName;
}
对于学生的每个对象non-static
属性 id 和 name 将以其初始值(0 & null)加载到内存中,每个对象的 id 和 name 可以不同。但是 collegeName 只会被加载一次,那是加载类执行的时候。所以对于 Student
的每个对象将具有相同的大学名称。这就是 static
的意思.
访问静态和非静态变量
class Student {
private int id;
private String name;
static String collegeName;
public static void main(String[] args) {
String s1 = Student.collgeName;
String s2 = collgeName;
Student student = new Student();
String s3 = student.name;
int id = student.id;
}
}
静态变量可以直接使用它们的名称或使用类名的帮助来访问。当有静态全局变量和局部变量时,静态的要和类名一起使用
public static void main(String[] args) {
String s1 = Student.collgeName;
String collgeName = "foo";
String output = collgeName;
}
在这里output
将具有值“foo”。局部变量总是比全局静态变量具有更高的优先级,这就是为什么 String output = s1;
将为输出提供值 null
.
在静态 block 内 non-static
必须在引用变量的帮助下访问变量(我们必须创建一个对象)。 Main 方法是静态的,这就是我们必须创建 Student
对象的原因访问 id
的值和 name
,否则会报编译时错误。
关于非静态 block 的盲目规则
每个非静态 block 都将使用默认的 this
代表当前引用的关键字,当使用类级别(静态和非静态)变量时调用 block 。示例 Java 代码
class Student {
private int id;
private String name;
static String collegeName;
void setData() {
id = 1;
name = "foo";
collegeName = "FooCollege";
}
public static void main(String[] args) {
Student student = new Student();
student.setData();
}
}
这是编译相同代码获取类文件时发生的情况
class Student {
private int id;
private String name;
static String collegeName;
void setData() {
this.id = 1;
this.name = "foo";
this.collegeName = "FooCollege"; // which will be again as Student.collegeName
}
public static void main(String[] args) {
Student student = new Student();
student.setData();
}
}
在这里this
代表引用变量 student
从主要方法。 表示调用 block 的引用变量。
来到这个问题,main 方法创建一个 Test
对象及其引用 method1()
被调用。所以里面method1
this 只是引用变量 t
在 main 方法和 t
中创建是方法的局部引用变量。现在让我们以类文件格式重写代码
public void method1(int x) {
Test t = new Test();
this.x = 22; // or Test.x = 22;
y = 44; // or this.y = 44;
/*
Test object inside method1 and main method are in two different locations.
When we write this.y = 44; the y inside the main method object will be changed and not the one created inside method1.
*/
System.out.println("Test.x: " + Test.x);
System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y); // means the y inside the object created inside method1
System.out.println("y: " + y); // means the y inside the object created inside main method
}
关于java - java中局部变量和类变量的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48355880/