我是新手,不了解物件和方法我在Dog 類中撰寫了兩個方法,一個是getDogInfo,另一個是anotherDogInfo第一個方法是列印正確的值,另一個是列印 null 為什么是這樣,我在這段代碼中做錯了什么?
public class Dog {
String breed;
String name;
int life;
public void getDogInfo() {
System.out.println("His name: " name);
System.out.println("His lifespan: " life);
System.out.println("His Breed: " breed);
}
public void anotherDogInfo() {
Dog laila = new Dog();
laila.name ="laila";
laila.life = 9;
laila.breed = "huskey";
System.out.println("His name: " name);
System.out.println("His lifespan: " life);
System.out.println("His Breed: " breed);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Dog charlie = new Dog();
charlie.name = "charlie";
charlie.breed = "DoberMan";
charlie.life = 15;
charlie.getDogInfo();
System.out.println("-----------------------------");
Dog laila = new Dog();
laila.anotherDogInfo();
}

uj5u.com熱心網友回復:
在anotherDogInfo中,當您進行列印時,您使用的是當前物件中的值,而不是您創建的物件中的值 ( laila)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/478581.html
上一篇:如何為物件添加值并洗掉當前值?
