【问题标题】:How methods access instance variable in java [duplicate]方法如何访问java中的实例变量[重复]
【发布时间】: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!

【问题讨论】:

标签: java class oop object


【解决方案1】:

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

  }
}

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 2016-06-22
    • 2021-06-03
    • 1970-01-01
    相关资源
    最近更新 更多