简体   繁体   中英

creating new instance in java classes

I'm new in java and I saw this sample code. I don't know why in JavaApplication.java file we need to create a new instance by new keyword to set the goat name but in Tiger.java there is no need to create a new instance by new keyword to set the goat name! what's the difference?

JavaApplication.java

public static void main(String[] args) {
    Tiger t = new Tiger();
    Goat g = new Goat();
    Goat g1 = new Goat();
    g.name = "goaty";
    g1.name = "goatia";
    t.name = "woofy";
    t.hunt(g);
    t.hunt(g1);
}

Tiger.java

public class Tiger {
    String name;
    void hunt(Goat food) {
        System.out.println(name + " ate " + food.name);
    }
}

Goat.java

public class Goat {
    String name;
}

In Tiger class inside the function hunt , food is a parameter of type Goat and a parameter doesn't need to be instantiated by the new keyword. Only the object needs to be instantiated.

I'm also new at java but what I understand in java is that you can't link non-static method/variable to a static one and in order to do so, you need to create an instance for it. :) the new keyword is needed to create an instance of it btw..

据我所知,您已将山羊食物放置为参数,这意味着hunt方法将接受山羊类型的对象,基本上食物是山羊类型的引用变量。因此,山羊可以做的任何事情也应适用于食物。类中只有一个名称字段。因此,每当创建一个对象时,都可以给它一个名称。现在,您要将Goat对象传递到您的方法中,以便打印出food.name您的山羊需要先具有一个名称。

A Goat can be created only by using the 'new' keyword. After a goat is created you can give this goat to a tiger to eat. So this goat here

 void hunt(Goat food) {
    System.out.println(name + " ate " + food.name);
}

is already created so you don't have to create it again. Of course you can initate it again but it would be pointless since if a tiger could create a goat by itself it would not need to hunt goats.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM