简体   繁体   English

在Java类中创建新实例

[英]creating new instance in java classes

I'm new in java and I saw this sample code. 我是Java的新手,我看到了此示例代码。 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! 我不知道为什么在JavaApplication.java文件中我们需要通过new关键字创建一个新实例来设置山羊名,但是在Tiger.java中,不需要通过new关键字创建一个新实例来设置山羊名! what's the difference? 有什么不同?

JavaApplication.java 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 老虎.java

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

Goat.java 山羊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. 在函数hunt内的Tiger类中, foodGoat类型的参数,不需要通过new关键字实例化该参数。 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. 我也是java的新手,但是我在java中了解的是,您不能将非静态方法/变量链接到静态方法/变量,为此,您需要为其创建实例。 :) the new keyword is needed to create an instance of it btw.. :)需要new关键字来创建它的一个实例。

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

A Goat can be created only by using the 'new' keyword. 只能通过使用'new'关键字来创建山羊。 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. 当然,您可以再次初始化它,但是这毫无意义,因为如果老虎可以自己创造山羊,那么就不必狩猎山羊。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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