Java Ссылка на класс - PullRequest
       1

Java Ссылка на класс

0 голосов
/ 29 января 2020
Animal remove = te.head;
te.head.size = 8;
te.head = null;



System.out.print(remove.getSize()); //gets 8, not null

для класса Animal

class Animal{
    int size;

    public Animal(int data) {
       this.size = data; 
    }

    public int getSize() {
       return this.size;
    }
}

Мне очень трудно понять, что переменная "remove" ссылается на "te.head", и при использовании метода "getSize ()" возвращает 8, а не ноль ,

Я java новичок. Пожалуйста, объясните, почему «remove.geSize ()» не возвращает нулевую ошибку. оно должно быть нулевым, верно?

1 Ответ

0 голосов
/ 29 января 2020

Объяснения внутри кода:

public class StackOverflowTest {
    public static void main(String[] args) {
    // creating one Animal and setting teHead to point to it
    Animal teHead = new Animal(9);  

    // setting a new reference to the same Animal
    // now there are two references pointing to the same Object
    Animal remove = teHead;         

    // Changing the content of the Animal
    teHead.size = 8;
    System.out.println(remove.getSize());

    // teHead is now not pointing anywhere. But remove is still pointing to Animal
    teHead = null;   
    System.out.println(remove.getSize());
    // Using teHead now will give a NullPointerException
//    System.out.print(teHead.getSize());

    remove = null;   // Now nothing is pointing to Animal

    // Using remove now will give a NullPointerException
//    System.out.print(remove.getSize());
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...