Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Casting
-
Casting forces a variable of one type to become a variable of another type.
-
To cast, you must preceed the variable to be casted with the type to which
you wish to cast in parenthesis. In other words, to cast a long to
an int:
long l = 12345;
int i = (int)l;
-
This casts the long variable l to an int variable, so that it can be assigned
to i.
-
The same deal goes for objects. To convert a Vehicle to a Hybrid:
public void run(Vehicle v) {
Hybrid h = (Hybrid)v;
}
-
You would only really want to do this if you want to take advantage of
fields and/or methods that are declared for the first time in the subclass.
In this example, you can use the method setElectricMode() only
after casting.
-
You must implicitly cast when going from a superclass to a subclass.
This is because Java wants you to confirm that you know what you are doing,
since subclasses have more functionality than superclasses. Going
the other way is no problem, because we know that the superclass has all
of the fields and methods of the subclass. Further, we know that
with dynamic casting, Java will use the method or field that appears at
the lowest level of granularity.
-
If you attempt to cast a superclass to a subclass that is not the true
subclass of the object, an exception is thrown. We'll get in to exceptions
later in this quarter, but let's just say that they can be caught, but
they are nasty.
-
If you want to confirm that a class is a certain type, use the instanceof
operator.
if (v instanceof Hybrid) {
h = (Hybrid)v;
}
-
This works fine. Interstingly, notice that instanceof is an operator,
not a method. Also notice that the 'o' in 'of' is lower case.
This might get you on a certification exam.
-
If the classes are in no way related, (changing a String to an Integer,
for instance), the compiler will not allow you to do it. You can
cast only within inheritance hierarchy.
-
Keep in mind, all classes derive from class Object, so all classes are
subclasses of Object.
-
In general, casts are bad. Unless you are using something like a
Vector that stores Objects types, try to avoid them. If you catch
yourself using one, try to think of a better way to program.
Abstract Classes



Created by: Brandan
Jones January 4, 2002