java - java中方法如何访问实例变量
问题描述
我正在学习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 关键字的情况下访问大小变量。
输出:
Wooof! Wooof!
Yip! Yip!
Ruff! Ruff!
解决方案
this
关键字在java中是可选的。在此示例中,您也可以实际使用此关键字。唯一需要强制使用它的场景是在引用本地和全局名称相同的字段时。
例子:
class Test
{
private int size; //global
public void method(int size)
{
this.size = size; //this.size refers to the declaration within the class, not the method local variable
}
}
推荐阅读
- python - 用 Python 重写 .txt 中的单个单词
- javascript - Reactjs Web 应用程序中下拉列表的 Jest 测试用例
- android - 如何多次推送 LiveData 的价值?
- automationanywhere - 如何在 Automation Anywhere 中的文件名后附加今天的日期?
- php - 通过 GET 方法提交表单时出现错误 403
- android - 是否可以使用本机控制器在 oculus quest 中复制/粘贴文本?
- azure - 如何使用 powershell 在 azure 上停止和启动逻辑应用程序?
- intellij-idea - 在 intellij IDEA 中编辑 web 模块
- amazon-dynamodb - 如何根据项目的其他属性值在 DynamoDBMapper 中自动生成属性
- r - 如何根据查找表更改数据框列的属性