Java中对象的引用[关闭]

问题描述 投票:-1回答:1

我是Java新手。在此代码片段中,为什么 - if(t.canRecord == true) - 当为Object时,只存储引用并且不覆盖现有值。

class TapeDeck 
{
  boolean canRecord = false;

  void playTape() 
  {
    System.out.println("tape playing");
  }

  void recordTape() 
  {
    System.out.println("tape recording");
  }
}

class TapeDeckTestDrive 
{
  public static void main(String [] args) 
  {
    TapeDeck t=new TapeDeck();
    t.canRecord = true;
    t.playTape();
    if (t.canRecord == true) 
    {
      t.recordTape();
    }
  }
}
java object reference
1个回答
2
投票
  • 在static main方法中,您将创建TapeDeck的新实例。对于此实例,canRecordis的值设置为false
  • 由于canRecord未设置为私人可见性,因此您可以通过t.canRecord直接访问它。通过t.canRecord = true你不是压倒性的,而是用false覆盖true的现有价值。
  • if-条件评估为trueas(i)t.canRecordtrue和(ii)与true中的trueresults的比较。
© www.soinside.com 2019 - 2024. All rights reserved.