首页 > 解决方案 > 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!

标签: javaclassoopobject

解决方案


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

  }
}

推荐阅读