In: Computer Science
public class GreeterTest
{
public static void main(String[] args)
{
// create an object for Greeter class
Greeter greeter = new Greeter("Jack");
// create two variables
Greeter var1 = greeter;
Greeter var2 = greeter;
// call the sayHello method on the first Greeter variable
String res1 = var1.sayHello();
System.out.println("The first reference " + res1);
// Call the setName method on the secod Grreter variable
var2.setName("Mike");
String res2 = var2.sayHello();
System.out.println("The second reference " + res2);
}
}
public class Greeter
{
public Greeter(String aName)
{
}
public void setName(String newName)
{
this.Name = newName;
}
public String sayHello()
{
return "Hello, "+ Name + "!";
}
private String Name;
}
The output will be
The first reference Hello, null!
The second reference Hello, Mike!
How to change the first sentence to "The first reference Hello, Jack!"
Please find the code here:
Name is not initialized in the constructor of Greeter class. So it is printing null.
public class GreeterTest
{
public static void main(String[] args)
{
// create an object for Greeter class
Greeter greeter = new Greeter("Jack");
// create two variables
Greeter var1 = greeter;
Greeter var2 = greeter;
// call the sayHello method on the first Greeter variable
String res1 = var1.sayHello();
System.out.println("The first reference " + res1);
// Call the setName method on the secod Grreter variable
var2.setName("Mike");
String res2 = var2.sayHello();
System.out.println("The second reference " + res2);
}
}
class Greeter
{
public Greeter(String aName)
{
this.Name = aName;
}
public void setName(String newName)
{
this.Name = newName;
}
public String sayHello()
{
return "Hello, "+ Name + "!";
}
private String Name;
}
OUTPUT:
The first reference Hello, Jack!
The second reference Hello, Mike!