86.8k views
5 votes
Solve the following questions.

After write a method for each question, you need to write a class 'TestNameClass' in a separate file, which includes a main method. In your main method, create two object of class Name type and test each method you defined in the Name class.

1. Create a class called Name that represents a person's name. The class should have fields representing the person's first name, last name, and middle initial. (Your class should contain only fields for now.)

2. Add two new methods to the Name class: public String getNormalOrder ( ) Returns the person's name in normal order, with the first name followed by the middle initial and last name. For example, if the first name is "John", the middle initial is "Q" and the last name is "Public", returns "John Q. Public". public String getReverseOrder ( ) Returns the person's name in reverse order, with the last name preceding the first name and middle initial. For example, if the first name is "John", the middle initial is "Q", and the last name is "Public", returns "Public, John Q.".

3. Write a toString method for the Name class that returns a String such as "John Q. Public". 4. Add a constructor to the Name class that accepts a first name, middle initial, and last name as parameters and initializes the Name object's state with those values.

5. Encapsulate the Name class. Make its fields private and add appropriate accessor methods to the class.

6. Add methods called setFirstName, setMiddleInitial, and setLastName to your Name class. Give the parameters the same names as your fields, and use the this keyword in your solution.

User Sayan Sen
by
5.4k points

1 Answer

3 votes

Answer:

The codes for the problem are given below

Step-by-step explanation:

//Name class

public class Name

{

private String first,last,middle;

public Name(String first,String middle,String last)

{

this.first=first;

this.middle=middle;

this.last=last;

}

public String getNormalOrder()

{

return first+" "+middle+". "+last;

}

public String getReverseOrder()

{

return last+", "+first+" "+middle+".";

}

public String toString()

{

return first+" "+middle+" "+last;

}

public void setFirstName(String first)

{

this.first=first;

}

public void setMiddleName(String middle)

{

this.middle=middle;

}

public void setLastName(String last)

{

this.last=last;

}

}

//TestNameClass class

public class TestNameClass

{

public static void main(String[] args)

{

Name myname=new Name("John","K","Watson");

myname.setFirstName("John");

myname.setMiddleName("Q");

myname.setLastName("Public");

System.out.println("My name: ");

System.out.println(myname.getNormalOrder());

System.out.println(myname.getReverseOrder());

Name friend=new Name("Sherlock","P","Holmes");

System.out.println("Friend's name: ");

System.out.println(friend.getNormalOrder());

System.out.println(friend.getReverseOrder());

}

}

User Crantok
by
5.5k points