Object: The Father of All Classes Casting and Classes: More On Inheritance
Object: The Father of All Classes Casting and Classes: More On Inheritance
Overview
1
Object: The father of all classes
Every class that does not specifically extend another class is a subclass of the class Object.
Thus every class directly or indirectly inherits from the standard class, Object.
If we have:
class Parent {
int size;
}
The compiler automatically converts it to:
class Parent extends Object {
int size;
}
toString()
Returns a String value of this Object.
The toString, equals and clone methods are often overridden when classes
are created
3
Casting and Classes … Up-Casting
Just like Java allows a smaller primitive type (e.g. int) to be assigned to a bigger type
(e.g. double), It also allow a reference to a subclass object to be assigned to a
reference variable of a super class object .
This is called up-casting because we are moving up the inheritance tree.
Example: Suppose we have the following.
class Parent {
int data;
}
class Child extends Parent {
String name;
}
Then we could have the following:
Object object;
Parent parent;
Child child = new Child();
parent = child;
object = child;
4
Casting and Classes … Up-Casting
Up-casting is very useful because it allows a single method to be written to handle all classes
derived from a single class.
For example, suppose we are writing an a application to print the standing of students based on
their GPA:
class TestReserchAssistant {
static String standing(Student s) {
if (s.getGPA() <= 2.0)
return "Under Warning";
else
return "Good Standing";
}
static void main (String[] args) {
Student s = new Student(991234,"Ahmed", 1.95);
ResearchAssistant ra = new ResearchAssistant(995678, "Imran", 3.45, 15);
s.print();
System.out.println(standing(s));
ra.print();
System.out.println(standing(ra));
}
}
Notice that the standing method can be called with ether Student or ResearchAssistant object.
5
Casting and Classes … Down-Casting
Java does not automatically allow a reference to a super class object to be assigned to a
reference variable of a subclass type. However, we can force it by using casting. This is
called down-casting.
e.g. Object object;
Parent parent;
Child child;
........
parent = (Parent) object;
child = (Child) parent;
Here we are taking a serious risk. If the original object was created from the super class and
we now cast it to a subclass type, then if we try to access a method that does not exists in the
super class, it will result in run-time error.
How ever, if the object was originally created from the subclass, then up-casted to super class
type and then down-casted back to sub-class type, then there is no problem.
We can always know the class from which an object is created by using the instanceOf
operator.
In fact it is safer to always do the following:
if (parent instanceOf Child)
child = (Child) parent;
6