Java Reference
In-Depth Information
return (goodPower == (( Superhero)other) .goodPower && respect == ((
Superhero)other) . respect ) ;
}
}
The method first calls super.equals . This calls the equals method for the
FictionalCharacter class. It checks if the two objects have the same type and the same
name. Only if we know that this is true should we compare them for the values of goodPower
and respect . When we know that the input object is of the same runtime type as the this
object, that is, it is of type Superhero , we can cast the input object to an object of type
Superhero and compare the variables goodPower and respect of the two objects.
8.14 Summary
The chapter covered issues related to inheritance and the Object class. We showed
that inheritance is similar to class composition. However, there are some subtle differences.
While a class can contain a null pointer to an object of a different class, the super object
can never be null. To guarantee this, Java creates the super object as the first operation in
the constructor of the subclass. Inheritance also allows for polymorphic method calls, while
this feature is not supported when class composition is used.
Polymorphism means that one of several methods may be executed using the same
syntax. Every object has a runtime and a compile-time type. The compile-time type of an
object is the type that is declared in the program. However, during program execution, the
object may reference an object that belongs to one of the subclasses, which becomes the
runtime type of the object. When calling a non-private instance method on an object, the
runtime type of the object is used to determine the method that will be executed.
The chapter also explains how abstract classes and interfaces work. An abstract class
is a class that cannot be instantiated. An abstract class may contain an abstract method
with no bodies, but it does not need to. All abstract methods need to be overridden in the
subclasses. Alternatively, an interface contains only abstract methods and constants. Java
allows a class to implement multiple interfaces.
Lastly, the chapter covered some of the methods of the Object class, including the clone
and equals methods. The chapter also covered the interface Cloneable and the compareTo
method. These are all methods that are part of Java and are usually overridden by the
programmer.
8.15 Syntax
￿ class C extends A {
...
}⇒
The C class inherits from the A class.
￿ class C implements A {
...
}⇒
The C class implements the A interface.
￿ super
Reference to the super object.
Returns true if the two objects are equal.
￿
o1.equals(o2)
 
Search WWH ::




Custom Search