Java Reference
In-Depth Information
g. Is orange instanceof Fruit ?
h. Is orange instanceof Apple ?
i.
Suppose the method makeAppleCider is defined in the Apple class. Can fruit
invoke this method? Can orange invoke this method?
j.
Suppose the method makeOrangeJuice is defined in the Orange class. Can
orange invoke this method? Can fruit invoke this method?
k. Is the statement Orange p = new Apple() legal?
l.
Is the statement McIntosh p = new Apple() legal?
m. Is the statement Apple p = new McIntosh() legal?
11.27
What is wrong in the following code?
1 public class Test {
2 public static void main(String[] args) {
3 Object fruit = new Fruit();
4 Object apple = (Apple)fruit;
5 }
6 }
7
8 class Apple extends Fruit {
9 }
10
11 class Fruit {
12 }
11.10 The Object 's equals Method
Like the toString() method, the equals(Object) method is another useful
method defined in the Object class.
Key
Point
Another method defined in the Object class that is often used is the equals method. Its
signature is
public boolean equals(Object o)
This method tests whether two objects are equal. The syntax for invoking it is:
object1.equals(object2);
The default implementation of the equals method in the Object class is:
public boolean equals(Object obj) {
return ( this == obj);
}
This implementation checks whether two reference variables point to the same object using
the == operator. You should override this method in your custom class to test whether two
distinct objects have the same content.
The equals method is overridden in many classes in the Java API, such as java.lang
.String and java.util.Date , to compare whether the contents of two objects are equal.
You have already used the equals method to compare two strings in Section  4.4.7, The
String Class. The equals method in the String class is inherited from the Object class
and is overridden in the String class to test whether two strings are identical in content.
 
 
 
Search WWH ::




Custom Search