类 和 Java 中的对象

Classes And Objects in Java

我是新手,不了解 Object 的Method 的 我在 Dog [=] 中写了两个方法28=] 一个是 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();
        
    }

anotherDogInfo 中,当您进行打印时,您使用的是当前对象中的值,而不是您创建的对象中的值 (laila)。

你犯的错误:

  1. 您已经两次创建对象 laila,一次在 main() 函数中,另一次在另一个 DogInfo() 方法中。
  2. 您必须在 main() 方法中创建对象。

解决方法: 试试这段代码,它运行良好。

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