Share
Explore BrainMass

Java programming - Person Runner

Using the Person and PersonRunner classes below, execute the main method in PersonRunner. Why does the program end abnormally? Comment out the first two lines and run the program again. Why does the reference to p3 cause Frank's name to be printed when we set Frank's name with the p2 reference?
public class PersonRunner
{
public static void main(String[] args)
{
Person p1 = null;
p1.speak();
Person p2 = new Person("Beth");
p2.speak();
Person p3 = p2;
p2.speak();
p2.setName("Frank");
p3.speak();
}
}

public class Person
{
private String name;

public Person(String name)
{
this.name = name;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void speak()
{
System.out.println("My name is " + name);
}
}

Solution Preview

Dear student,

Please find below the solution.

Thanks,
Kavita Narang

(--Please note that my work should only be used as a guidance and not be copied into your assignments.
The answers available here are meant for assistance and the understanding of challenging academic topics.
Use the solution alongside your own work and watch your knowledge and grades ...

Solution Summary

The solution answers all the questions regarding the failure of given program. And then go on to explain what happens when we modify the program and why there are any problems/errors.

$2.19