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;
}
name.void hunt(Goat food) {...}method in Tiger.java, you aren't creating a new Goat object. Instead, you're expecting a Goat object (created somewhere) to be passed on tohuntmethod.