Reputation: 297
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;
}
Upvotes: 1
Views: 340
Reputation: 8841
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.
Upvotes: 1
Reputation: 45
As far as i can see you have placed Goat food as parameter which means hunt method will accept an object of type Goat basically food is reference variable of type Goat.So any thing that a Goat can do should apply to food also.In your Goat class you have only a field of name .So whenever you create an object you can just give it a name that's it .Now you are passing Goat object into your method so in order to printout food.name your goat needs to have a name first.
Upvotes: 1
Reputation: 59
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.
Upvotes: 2
Reputation: 19
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..
Upvotes: 1