Question

In: Computer Science

Read the lecture for Chapter 7, the following text and then answer the question at the...

Read the lecture for Chapter 7, the following text and then answer the question at the end. Notice the grading criteria this week is different than other weeks

Constructors

Constructor methods inside a class are methods that determine how an object is going to be created when some program instantiate one of them using the “new” clause. Their main use is to initialize the object’s instance variables. For example, last week I presented the Chair class that represented chairs. This class had the following instance variables:

private String color;    // instance variable for color of the Chair                  private int numberOfLegs;    // instance variable to hold # of legs

The following are two appropriate constructors that could be included in that class:

public Chair (String newColor, int newNumberOfLegs ) {
this.setColor(newColor);
this.setNumberOfLegs(newNumberOfLegs);

}

public Chair ( ) {
              this (“brown”, 4);
}

The first constructor is a constructor with parameters. The second constructor, without parameters, is called the “default” constructor. All constructors other than the “default” are known as the “overloaded” constructors.

In both constructors all that we are doing is given initial values to the instance variables “color” and “legs”. In the default constructor we use “default” values (that is the reason for the constructor’s name). In the overloaded constructor we take the values provided by whoever is creating the object to initialize its instance variables. This method uses the mutator methods of the class to avoid code repetition.

Notice that the default constructor is actually calling the constructor with parameters, by passing the initial values to this constructor with the keyword “this”. The advantage of this approach is that it centralizes all the initializations into one method, the constructor. This makes the code easier to maintain in the future, because we potentially will need to modify only one constructor if something changes.

Notice also that the call to a constructor from another constructor does not need the dot (".") after the keyword "this". This is the only place where "this" is not followed by a dot.

A driver program may use these constructors as follows:

firstChair = new Chair();                  // Using default constructor
        secondChair = new Chair(“red”, 3);   // Using overloaded constructor

The equals method

When we want to compare objects we need to define what do we mean by equal. For example if I have two chairs, how can I say they are equal? Are they equal if they have the same color alone? Should they also have the same number of legs? What about shape? Should they have the same shape? If I am trying to match chairs in a living room, certainly all these factors should be taken into consideration, but what if all I want to do is to sit? I really do not care what’s the chair color or the number of legs, as long as I can sit on it. To me, all chairs where I can sit will be equal. So the idea of equality depends of the context. That is why when describing an object we have the opportunity to indicate exactly what “equal” means. We do this by writing an appropriate equals method. In this method we compare the only thing we can compare in objects, their attributes, also known as their instance variables. This method will check if the attributes of the objects we are comparing are the same. We are free to select which attributes we are going to compare. It is our definition of equality after all! For example, last week I presented the Chair class that represented chairs. This class had only two instance variables, the chair’s color (color) and its number of legs (numberOfLegs). The following is an equals method that will check if both, the color and the number of legs, in two chairs are the same. If that is the case the equals method will return true, otherwise it will return false:

public boolean equals (Chair secondChair) {
return ((this.getColor().equals(secondChair.getColor()) &&
(this.getNumberOfLegs() == secondChar.getNumberOfLegs()) )

}

The method receives as a parameter a second chair (secondChair) of type Chair. This secondChair object is going to be compared against the current object. That current object is represented by the keyword “this”. Therefore “this” represents the first object. First we are comparing the color of both chairs. We obtain the color using the accessor method from the Chair class, getColor. According to my definition of the getColor method, each time it is called it produces a String with the color of their respective chair, and because we are comparing Strings, we use the equals method from the String class to compare them (We always should use the equals method when comparing reference objects). Similarly, we use the getNumberOfLegs accessor method to retrieve the number of legs of each chair. This method will return integer numbers, therefore they can be compared using the ‘==’ symbol (We always should use the ‘==’ symbol when comparing primitives). If both expressions are true, the whole expression is true, because they are connected by the AND connector (&&). So if both conditions are true, we can say that the Chair objects are equal, “this” chair and the second chair are equal. That is why we return the result of this logical expression. If any of the conditions is false, the whole logical expression is false, meaning that one of the attributes do not match, and that is why the chairs cannot be classified as equal. This false outcome is also returned in that sentence. Using two Chair objects (chair1 and chair2) we can compare them using the equals method as follows:

   
           if (chair1.equals(chair2)) {
               // actions when both Chair objects are equal
           }

We could also compare them the other way around, it will work exactly the same:

           if (chair2.equals(chair1)) {
               // actions when both Chair objects are equal
           }

In the first case chair1 will be the current object (this) and chair2 will be the second chair (secondChair) inside equals. In the second case, the roles are reversed.

Questions

In last week’s discussion thread you wrote a class description for some objects. This week you must refine your description by writing two constructors (a default constructor and a constructor with parameters) and an equals method to implement your definition of equality among your objects. Write the constructors and the equals method inside the class you created last week. Write testing code in the Class Driver to test your new constructor and equals method. Show also a screen capture of the driver running your programs.

Solutions

Expert Solution

In case of any query, do comment. Please rate answer. Thanks

Please use code as below:

==========================chair.Java==============================

public class Chair

{

    //data member

   private String color;     // instance variable for color of the Chair                 

   private int numberOfLegs; // instance variable to hold # of legs

  

   //getter and setters

   public String getColor()

   {

       return this.color;

   }

  

   public void setColor(String color)

   {

       this.color = color;

   }

  

   public int getNumberOfLegs()

   {

       return this.numberOfLegs;

   }

  

   public void setNumberOfLegs(int numberOfLegs)

   {

       this.numberOfLegs = numberOfLegs;

   }

  

   //Overloaded Constructor

   public Chair (String newColor, int newNumberOfLegs )

   {

   

        this.setColor(newColor);

        this.setNumberOfLegs(newNumberOfLegs);

    }

   

    //default constructor

    public Chair()

    {

        this ("brown", 4);

    }

    //equal method to compare two object based on choice. Here comparision between all the attributes of current object with second object

   

    public boolean equals(Chair secondChair)

    {

        return ((this.getColor().equals(secondChair.getColor()) &&

        (this.getNumberOfLegs() == secondChair.getNumberOfLegs())));

    }

   

    //to print the object information, you can remove it if you dont want to print this information

    @Override

    public String toString()

    {

        return "Chair is having " + this.getColor() + " color and number of legs are " + this.getNumberOfLegs() + ".";

    }

  

}

==========================Main driver program==========================

public class Main

{

              public static void main(String[] args) {

                             //Create three Chair object to show the equals functionality

                             Chair firstChair = new Chair();                  // Using default constructor

        Chair secondChair = new Chair("red", 3);   // Using overloaded constructor

        Chair thirdChair = new Chair("red", 3);

       

        System.out.println("**************************************************************");

        //to print the object information, you can remove below two lines if you dont want to print this information

        System.out.println(firstChair);

        System.out.println(secondChair);

       

        //Call equals here and print the output accordingly

        if (firstChair.equals(secondChair))

        {

            System.out.println("Chairs are equal.");

        }

       else

        {

            System.out.println("Chairs are not equal.");

        }

       

        System.out.println("**************************************************************");

        //to print the object information, you can remove below two lines if you dont want to print this information

        System.out.println(secondChair);

        System.out.println(thirdChair);

       

        //Call equals here and print the output accordingly

        if (thirdChair.equals(secondChair))

        {

            System.out.println("Chairs are equal.");

        }

        else

        {

            System.out.println("Chairs are not equal.");

        }

       

        System.out.println("**************************************************************");

              }

}

======================screen shot of the code===============================

Output:


Related Solutions

Consumer Decision Process,, Read Chapter 5 or listen to the lecture video on Chapter 5 (under...
Consumer Decision Process,, Read Chapter 5 or listen to the lecture video on Chapter 5 (under Course Content for this week). The lecture video discusses the consumer decision model first.   Think of a product that you purchased within the past six (6) months. Answer these questions relative to the purchased product. Your answers should align with how these stages are done based on the consumer decision model in the text.  Your submission should be attached, NOT typed in the submission box....
Read and review chapter 31 Analyze the following case study and answer the question bellow CASE...
Read and review chapter 31 Analyze the following case study and answer the question bellow CASE STUDY Mrs. Angstrom is an 83-year-old patient who was admitted to the hospital after she fell outside her home and broke her hip. She has been living alone in her apartment since her husband died 4 years ago. Mrs. Angstrom has no long-term history of mental illness, but she has recently shown signs of cognitive impairment and dementia, according to her neighbor Jeanine Finch,...
By now, you should have listened to the audio lecture, read the chapter, and taken the...
By now, you should have listened to the audio lecture, read the chapter, and taken the self-assessment and quiz. For this discussion activity, I want you to respond to the following question in the Discussion area in this learning module. Tower cranes have tall vertical, latticed masts or towers and horizontal booms called "jibs". There are several different types of jibs available for tower cranes. List at least three jibs and briefly describe each jib type.
By now, you should have listened to the audio lecture, read the chapter, and taken the...
By now, you should have listened to the audio lecture, read the chapter, and taken the self-assessment and quiz. For this discussion activity, I want you to respond to the following question in the Discussion area in this learning module. Clamshells are one of the special excavator types and sometimes clamshells are compared with draglines. List and discuss at least three different points between the two (Dragline vs. Clamshell) in terms of operations, productivity, etc. Do research on the internet,...
The eight training methods described in chapter 7 are the following, Audiovisual Instruction, Auto instruction, Lecture,...
The eight training methods described in chapter 7 are the following, Audiovisual Instruction, Auto instruction, Lecture, Modeling, on-the-job training, Role playing, and Stimulation. PLEASE summarize and describe all of them. Also can you give me an in depth description on "on-the-job training"???
Read the case study in this chapter and answer the following additional questions in two to...
Read the case study in this chapter and answer the following additional questions in two to three sentences. Chapter 10: Long-Term Care Comparative Health Information Management. 4th Edition Capstone Activity Are there any technology considerations that should be addressed? How could the facility better prepare in the future for their next survey?
Text 1. Read the text and answer the questions. A better life? China's expectations are rising,...
Text 1. Read the text and answer the questions. A better life? China's expectations are rising, with no end in sight. What's next? By Peter Hessler The beginning of a Chinese factory town is always the same: in the beginning, nearly, everybody is a construction worker. The growing economy means that everything moves fast, and new industrial districts rise in several stages. Those early labourers are men who have migrated from rural villages, and immediately they are joined by small...
Read the following text on Reliability Maintainability and Availability (RMA) analysis carefully and answer the questions....
Read the following text on Reliability Maintainability and Availability (RMA) analysis carefully and answer the questions. [8 Marks] The first step in defining Reliability Maintainability and Availability (RMA) requirements is to articulate a representative sample of mission scenarios in which the network is going to be used; these are documented in an anecdotal narrative that describes how the usage will occur, when, what is necessary for this mission to succeed, and how important it is to network users. This includes...
Please read the text below and answer the following questions.. Santa Barbara is a small (imaginary)...
Please read the text below and answer the following questions.. Santa Barbara is a small (imaginary) nation in Central America. Universidad Nacional de 
Santa Barbara (the National University of Santa Barbara) is the most prestigious 
university in the region. The main campus is in the capital, Ciudad de Santa Barbara, and 
enrolls more than 25,000 students in bachelor's, master's, and doctoral programs covering 
a wide variety of academic disciplines. Three regional campuses enroll approximately 
10,000 additional students.
A meeting is...
Read Chapter 12 of the text and watch the Connect video “Kitty Genovese and the Bystander...
Read Chapter 12 of the text and watch the Connect video “Kitty Genovese and the Bystander Effect.” In your initial post, address the following: Briefly describe your reaction to the video. Were you shocked by the bystanders’ unwillingness to help? Why do you think they did not help? In what ways has a current event impacted your willingness to help? Think about your own morals here and the concern for the safety of yourself and your loved ones if presented...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT