【发布时间】:2019-11-10 03:41:58
【问题描述】:
我正在学习java,遇到一个疑问。就像在python中访问类变量一样,我们使用self,但在java中,同样的事情是完成的,但没有this或self。
class Dog {
int size;
String name;
void bark() {
if (size > 60) {
System.out.println(“Wooof! Wooof!”);
} else if (size > 14) {
System.out.println(“Ruff! Ruff!”);
} else {
System.out.println(“Yip! Yip!”);
}
}
}
class DogTestDrive {
public static void main (String[] args) {
Dog one = new Dog();
one.size = 70;
Dog two = new Dog();
two.size = 8;
Dog three = new Dog();
three.size = 35;
one.bark();
two.bark();
three.bark();
}
}
三个对象如何在不使用 this 关键字的情况下访问 size 变量。
输出:
Wooof! Wooof!
Yip! Yip!
Ruff! Ruff!
【问题讨论】:
-
this关键字在 Java 中是可选的,正如在 this question's answers 中广泛讨论的那样。