I'm a moderately experienced C++ guy learning Java. I'm struggling to understand references that "point" to a specific instance of an object. In C++, this would be easy. But the more I Google "java reference to an instance object," the more I read and the more confused I get about how this sort of thing works in Java.
Let me illustrate a specific example. Suppose I wanted to create a boxing simulation. Below is (abbreviated) code which sets up the boxers and lets them duke it out. At the end of the fight, I'd like a "WinnerReference" reference to "point" to the last boxer standing:
public class Boxer {
String Name;
public Boxer(String a) {
Name = a;
}
String GetName() { return Name; }
}
public class BoxingRing {
public BoxingRing() {
// Do nothing
}
void FightFightFight(Boxer a, Boxer b, >>WinnerReference<< )
// Boxers fight here
// WinnerReference is pointed to winning boxer here
}
}
public class BoxingMatch {
public static void main(String[] args) throws IOException {
Boxer Joe = new Boxer("Joe");
Boxer Sam = new Boxer("Sam");
BoxingRing TheRing = new BoxingRing();
// Create reference called "WinnerReference" of type Boxer here
TheRing.FightFightFight(Sam, Joe, WinnerReference);
System.out.println("The winner of this boxing match was: " + WinnerReference::GetName());
}
}
I've been researching this all afternoon, but can't find a tutorial which directly leads me through what I'm trying to do. (You can probably see that I'm approaching this from a C++ perspective.)
What I'd like to ask the forum is this: Is this a feasible approach for for a Java program? Am I Googling for the correct terminology? Is there a good resource someone could recommend?
Many thanks! -P
At the end of the fight, I'd like a "WinnerReference" reference to "point" to the last boxer standing
It sounds like you're looking for pass-by-reference. That doesn't exist in Java - all values are passed by value, but for any non-primitive types the value of the expression is a reference anyway. That's not the same as pass-by-reference though.
Generally, the best way to get round this limitation - is to simply use a return value instead:
Boxer fightFightFight(Boxer a, Boxer b) {
// Boxers fight here
return winner; // Or whatever
}
Then in your calling code:
Boxer winner = ring.fightFightFight(sam, joe);
It's important to understand that you won't be creating any new Boxer
objects here (unless you do so explicitly, of course) - you'll just be returning a reference to one of the existing ones.
In C++, this would be somewhat equivalent to
Boxer* fightFightFight(Boxer *a, Boxer *b)
... if that helps!
(It would be a good idea to start following Java naming conventions right now, by the way.)
See more on this question at Stackoverflow