I have come across this snippet in a Java book (Walter Savitch):
/**
Class whose privacy can be breached.
*/
public class PetPair
{
private Pet first, second;
public PetPair(Pet firstPet, Pet secondPet)
{
first = firstPet;
second = secondPet;
}
public Pet getFirst()
{
return first;
}
public Pet getSecond()
{
return second;
}
public void writeOutput()
{
System.out.println("First pet in the pair:");
first.writeOutput();
System.out.println("\nSecond pet in the pair:");
second.writeOutput();
}
}
What I don't understand is why the method "writeOutput" has, within its body, a call to writeOutput itself. How can a method have the same method within it, i.e., how can a method call itself?? I can understand a method calling ANOTHER method, but this does not make sense to me!
I did not try anything. I did not try running the programme on Eclipse. Why? Because I don't understand the idea behind a method calling itself. If someone could explain this to me, I'd happily run the programme and see the output. I'm sure the programme runs, cause I got it from a book, but running it won't do me any good cause I don't understand the basis.
What I don't understand is why the method "writeOutput" has, within its body, a call to writeOutput itself.
the method "writeOutput" doesn't call it self, it calls the method writeOutput in the Pet object "first" then it calls the method writeOutput on the Pet object "second".
its calling a method called writeOutput that is in the Pet class not the writeOutput method it self.
if it actually wants to call it self it would call it self as "this.writeOutput()"