In: Computer Science
For this question you need to write some methods and class headers.
(a) Assume that you have written a Rectangle class with instance variables length and width. You have already written all set and get methods and area and perimeter methods. Write an equals() method that takes Object o as a parameter. The method should return true when the Object o is a rectangle with the same length and width.
Answer:
(b) A class named Fruit implements an interface called Edible. The interface has a single method called howToEat(). A class called Orange extends Fruit and implements Edi- ble. Write the class header for the Orange class and override the howToEat() method of the Fruit class. The method should print a brief message to the screen about how to eat an orange. Do not write any other methods or constructors.
Answer:
Here is the completed code for each problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
Answer for question 1
public boolean equals(Object ob) {
// checking if ob is a Rectangle
if (ob instanceof Rectangle) {
// safe type casting ob to Rectangle
Rectangle other = (Rectangle) ob;
// returning true if both rectangles have same length and same width
return this.length == other.length && this.width == other.width;
}
// if ob is not a Rectangle or the dimensions mismatch, returning false.
return false;
}
Answer for question 2
// required class header of Orange class extending Fruit class and implementing
// Edible interface. Note that it is not important to add 'implements Edible' to
// the class header, because the super class Fruit already implements Edible, so
// automatically, by inheritance, Orange class implements the Edible interface
class Orange extends Fruit {
// overriding howToEat method to display a brief message
@Override
public void howToEat() {
System.out.println("Peel it and then eat it.");
}
}