Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

public class Greeter { public Greeter(String aName) { name = aName; } public Str

ID: 667199 • Letter: P

Question

public class Greeter

{

public Greeter(String aName)

{

name = aName;

}

public String sayHello()

{

return "Hello, " + name + "!";

}

private String name;

}

public class GreeterTester

{

public static void main(String[] args)

{

Greeter worldGreeter = new Greeter ("World");

String greeting = worldGreeting.sayHello();

System.out.println(greeting);

}

}

Write a method void swapNames(Greeter other) of the Greeter class that swaps the names of this greeter and another. Create two objects in the GreeterTesterclass and use the swapNames method to swap their names. You need to print their old names and their new names.

Explanation / Answer

public class Greeter
{
public Greeter(String aName)
{
name = aName;
}
public String sayHello()
{
return "Hello, " + name + "!";
}
private String name;
}
public class GreeterTester
{
public static void main(String[] args)
{
Greeter worldGreeter = new Greeter ("World");
String greeting = worldGreeting.sayHello();
System.out.println(greeting);
}
}

class Greeter {
private String name;

public void swap( Greeter other ){

}

Greeter greetsDave = new Greeter( "Dave Clark" );
Greeter greetsJane = new Greeter( "Jane Doe" );
System.out.println( greetsJDave.sayHello() );
System.out.println( greetsJane.sayHello() );
greetsDave.swapNames( greetsDave );
System.out.println( greetsDave.sayHello() );
System.out.println( greetsJane.sayHello() );