Chapter 8.
The Ultimate Superclass: Object
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
1
Polymorphism in Action
— OceanwasaskedtobuildasimpleDog-specificlist (pretending that we do not have the ArrayList class for the moment)
— Hecameupwiththefollowingdesign — Usearegulararraywithafixedlengthto
— Useanint valuetostoretheindexofthe next available position in the Dog array
— Implementanadd()methodforaddingaDogobjecttothe array at the next available position. When the array is full, the add() method will simply do nothing
— Implementaget() methodforretrievingaDogobjectfrom the array. If the index argument is out of bound, simply return null
MyDogList
Dog[] dogs int nextIndex
add(Dog d) get(int index)
store the Dog objects
2
Polymorphism in Action
— Below is Ocean’s first version of the Dog-specific list
public class MyDogList {
private Dog[] dogs = new Dog[5]; private int nextIndex = 0;
public void add(Dog d) {
if (nextIndex < dogs.length) {
dogs[nextIndex] = d;
System.out.println("Dog added at " + nextIndex);
nextIndex++; }
}
public Dog get(int index) {
if (index >= 0 && index < dogs.length) { return dogs[index];
} else { return null;
} }
}
3
Polymorphism in Action
— Cameasnosurprise,therewasaminorchangetothe specification that the list should keep Cats too
— Oceanhadafewoptionshere:
—
1. Makeaseparateclass,MyCatList,tostoreCatobjects
2. Makeasingleclass,MyDogAndCatList,thatkeeps2 different arrays as instance variables, and has 2 different add() methods (i.e., addDog() and addCat()) and 2 different get() methods(i.e.,getDog()andgetCat())
3. MakeaheterogeneousMyAnimalListclassthatcanstore any kind of Animal subclasses
The first 2 options are quite clunky, while the 3rd option sounds the best (more generic)
4
Polymorphism in Action
— BelowisOcean’srevisedversionoftheDog-specificlist
public class MyAnimalList {
private Animal[] animals = new Animal[5]; private int nextIndex = 0;
public void add(Animal a) {
if (nextIndex < animals.length) {
Don’t panic. We are not making a new Animal object from the abstract Animal class, but a new array object of type Animal!
}
5
animals[nextIndex] = a;
System.out.println("Animal added at " + nextIndex);
nextIndex++; }
}
public Animal get(int index) {
if (index >= 0 && index < animals.length) { return animals[index];
} else { return null;
} }
— Example
Polymorphism in Action
public class AnimalTestDrive {
public static void main(String[] args) {
MyAnimalList list = new MyAnimalList(); list.add(new Dog());
list.add(new Cat());
} }
— Sampleoutput
Animal added at 0 Animal added at 1
What about non-Animals?
Why not make the class generic enough to store anything?
To achieve this, we need a class above Animal, one that is the superclass of everything!
6
Polymorphism in Action
— EveryclassinJavaextendstheObjectclass
— Objectclassisthemotherofallclasses(i.e.,it
is the superclass of everything!)
— Anyclassthatdoesnotexplicitlyextend another class, implicitly extends the Object class
— Example
— DogextendsCanine,andCanineextendsAnimal
— SinceAnimaldoesnotexplicitlyextendanother class, it implicitly extends Object
— HenceDogextendsObject(indirectly)
Animal
food hunger location
makeNoise( ) eat() sleep() roam()
Canine
roam()
Dog
makeNoise() eat()
7
Polymorphism in Action
— WiththeObjectclassbeingthesuperclassofeverything, it is possible to create a list that can store anything!
ArrayList
add(Object elem)
Adds the object parameter to the list
remove(int index)
Removes the object at the index parameter
remove(Object elem)
Removes this object (if it is in the ArrayList)
contains(Object elem)
Returns true if there is a match for the object parameter
isEmpty()
Returns true if the list has no element
indexOf(Object elem)
Returns the index of the object parameter or −1 size()
Returns the number of elements currently in the list
get(int index)
Returns the object currently at the index parameter
...
8
The Ultimate Superclass: Object
Object
— Everyclassyouwriteinheritsallthe methods of the Object class
— Theclassesyouhavewritteninherit methods you do not even know you have
— Belowaresomeofthemethodsofthe Object class that you may be interested in
— equals()
— hashCode() — getClass() — toString()
boolean equals(Object o) int hashCode()
Class getClass()
String toString()
...
YourClassHere
9
The Ultimate Superclass: Object
— Theequals()method
— Comparestheobjectparameterwiththecurrentobject,and
returns true if they are thesame
— Implementsthemostdiscriminatingpossibleequivalence relation on objects, i.e., for any non-null reference values x and y, this method returns true if and only if both x and y are referencing the same object
— Youshouldoverridethismethodifyouwouldliketotest whether 2 objects are equal in the sense that they contain the same information (note that you should also override the hashCode() method as well in this case)
public boolean equals(Object obj)
10
The Ultimate Superclass: Object
— Example
Dog d = new Dog(); Cat c = new Cat();
if (d.equals(c)) { System.out.println("true");
} else { System.out.println("false");
}
— Sampleoutput
false
11
The Ultimate Superclass: Object
— ThehashCode()method
— Returnsahashcodevalue(integer)forthecurrentobject
(e.g., to be used with hash tables)
— Bydefinition,if2objectsareequalaccordingtothe equals() method, then calling the hashCode() method on each of the 2 objects must produce the same integer result
— Example:
— Sampleoutput:
2018699554
Typically, the Object class implements this method by converting the internal address of the object into an integer
public int hashCode()
Dog d = new Dog(); System.out.println(d.hashCode());
12
The Ultimate Superclass: Object
public final Class getClass()
— ThegetClass()method
— ReturnsaClassobjectthatrepresentstheruntimeclassof
the current object
— Thekeywordfinal meansthismethodcannotbe
overridden
— Example:
— Sampleoutput:
Dog d = new Dog(); System.out.println(d.getClass());
class Dog
13
The Ultimate Superclass: Object
— The toString() method
— Returnsastringthat“textuallyrepresents”thecurrent
object
— Recommendedthatallsubclassesoverridethismethod
— Example:
— Sampleoutput
Dog@7852e922
In the Object class implementation, this string is composed of the class name, the at-sign character @ and the unsigned hexadecimal representation of the hash code of the current object
public String toString()
Dog d = new Dog(); System.out.println(d.toString());
14
Using Object as a Polymorphic Type
If polymorphic types are so good, why don’t we just make all our methods take and return Object references?
— Thatdefeatsthewholepointof‘type-safety’,oneofJava’s greatest protection mechanisms for your code
— RecallthatJavaisastrongly-typedlanguage
— Thecompilercheckstomakesurethattheobjectonwhicha
method is being called is actually capable of responding
— Inotherwords,onecancallamethodonanobjectreference only if the class of the reference type actually has that particular method
15
Using Object as a Polymorphic Type
— Examples
FamilyDoctor d = new FamilyDoctor();
Doctor
workAtHospital
treatPatient()
d.treatPatient(); d.giveAdvice();
d is a FamilyDoctor reference and FamilyDoctor has a treatPatient()
method and a giveAdvice() method
Doctor d = new FamilyDoctor();
d.treatPatient();
d is a Doctor reference and Doctor
FamilyDoctor
makesHouseCalls
giveAdvice()
Doctor d = new FamilyDoctor();
d.giveAdvice();
This won’t compile!
d is a Doctor reference but Doctor does not have a giveAdvice() method
has a treatPatient() method
16
Using Object as a Polymorphic Type
— UsingObjectasapolymorphictypehasapricetopay — ConsideranArrayListdeclaredtoholdDogobjects,i.e.,
ArrayList
— WhenyouputanobjectintoanArrayList
as a Dog, and comes out as a Dog — Example:
ArrayList
myDogArrayList.add(aDog);
Dog d = myDogArrayList.get(0);
The get() method returns a Dogreference 17
Using Object as a Polymorphic Type
— NowconsideranArrayListdeclaredtoholdObject objects, i.e., ArrayList
Using Object as a Polymorphic Type
— Theproblemwithhavingeverythingtreated polymorphically as an Object is that the objects appear to lose their true essence
— Example:WhenaDogwon’tactlikeaDog
public class BadDog {
public static void main(String[] args) {
Dog dog = new Dog();
Dog sameDog = getObject(dog);
sameDog.makeNoise(); }
public static Object getObject(Object o) {
return o; }
}
This won’t compile!
getObject() returns an Object reference which cannot be assigned to a Dog reference variable
19
Using Object as a Polymorphic Type
— Example:WhenaDogwon’tactlikeaDog
public class BadDog2 {
public static void main(String[] args) {
Dog dog = new Dog();
Object sameDog = getObject(dog);
sameDog.makeNoise(); }
public static Object getObject(Object o) {
return o; }
}
This won’t compile!
The compiler decides whether you can call a method based on the reference type, not the actual object type. Note that the Object class does not have a makeNoise() method!
20
Objects are Object
— Anobjectcontainseverythingitinheritsfrom each of its superclasses
— Everyobject,regardlessofitsactualclass type, is also an instance of the Object class
— AnyobjectinJavacanbetreatednotjustas an instance of its own class, but also an Object
— Whenyoucreateanobject,saya Snowboard, you get a single object on the heap, but this object wraps itself around an inner core representing the Object portion of itself
Object
boolean equals(Object o) int hashCode()
Class getClass()
String toString()
…
Snowboard
turn() shred() getAir() loseControl( )
Object
Snowboard
21
Objects are Object
— Ifareferenceislikearemotecontrol,theremotecontrol takes more and more buttons as you move down the inheritance tree
— Aremotecontrol(reference)oftypeObjecthasonlyafew buttons (for the exposed methods of the Object class)
— AremotecontroloftypeSnowboardincludesallthebuttons from the Object class, plus any new buttons of the Snowboard class
— AnObjectreferencetoanobject,sayaSnowboard,can see only the Object portion of the object, and access only the instance variables and methods of the Object class
Snowboard
Object
Object Snowboard
22
Casting
— Acastcanbeusedtoassignanobjectreferenceofonetypeto a reference variable of a subtype, e.g.,
Dog dog = new Dog(); Object o = dog;
Dog sameDog = (Dog) o;
— Atruntime,acastwillfailiftheobjectontheheapisnotofa type compatible with the cast!
— Toplaysafe,usetheinstanceofoperatortocheckifanobject is an instance of a certain class before type casting, e.g.,
Object o = new Dog(); if (o instanceof Dog) {
System.out.println(“It is a Dog”); }
23
Casting
— Example:WhenaDogbecomesaDogagain
public class BadDog3 {
public static void main(String[] args) {
Dog dog = new Dog(); Object o = getObject(dog); if (o instanceof Dog) {
Dog sameDog = (Dog) o;
Casting an Object reference to a
} Dog object back to a Dog reference
}
sameDog.makeNoise();
public static Object getObject(Object o) {
return o; }
}
24
Chapter 8.
End
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
25