I am new to oops and not understanding Object's and Method's I have written two methods in Dog Class one is getDogInfo and other is anotherDogInfo the first method is printing correct values and other is printing null why is that, what am i doing wrong in this code ?
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();
}
CodePudding user response:
In anotherDogInfo
, when you do the printing, you're using the values from the current object instead of those from the one you created (laila
).