'Classes And Objects in Java

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();
        
    }

enter image description here



Solution 1:[1]

Mistakes you made:

  1. You have created the object laila two times i.e. one in the main() function and the other is in anotherDogInfo() method.
  2. You must create the object inside the main() method.

Solution: Try this code, it is working perfectly.

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() {
       
        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.name ="laila";
        laila.life = 9;
        laila.breed = "huskey";
        laila.anotherDogInfo();
        
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Raushan Kumar