In: Computer Science
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.
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: