|
ClassA x = new ClassA( ... ); // ClassA is the base class of ClassB ClassB y; ClassB z; x = y; // **** this is "upcasting" (discussed prviously) z = (ClassB) x; // **** Downcasting: casting a reference of // the base class (x of type ClassA) to // a derived class (y of type ClassB) |
|
public class Downcasting1
{
public static void main(String[] args)
{
BankAccount x; // x is a Base class variable
CheckingAccount y; // y and z are Derived class variables
CheckingAccount z;
/* -------------------------------------------------------
Remember that:
A derived class may have MORE variables/methods
than the base class !
------------------------------------------------------- */
/* --------------------------------
A legal downcasting scenario
-------------------------------- */
y = new CheckingAccount(343, "John", 2000.0);
x = y; // Upcasting, allowed (discussed before)
// x references a CheckingAccount object
z = (CheckingAccount) x; // Downcasting, allowed because:
// x references a CheckingAccount object
// z is a CheckingAccount reference var.
// ⇒ compatible !!!
}
}
|
How to run the program:
|
public class Downcasting2
{
public static void main(String[] args)
{
BankAccount x; // x is a Base class variable
CheckingAccount y; // y and z are Derived class variables
CheckingAccount z;
/* -------------------------------------------------------
Remember that:
A derived class may have MORE variables/methods
than the base class !
------------------------------------------------------- */
/* --------------------------------
An ILLEGAL downcasting scenario
-------------------------------- */
x = new BankAccount(343, "John", 2000.0);
// x references a BankAccount object
z = (CheckingAccount) x; // Downcasting, NOT allowed because:
// x references a BankAccount object
// z is a CheckingAccount reference var.
//
// Reason:
// A CheckingAccount object has
// MORE variables/methods than
// a BankAccount object.
// Some operations are NOT possible !
}
}
|
How to run the program:
|
Illustrating the reason why not allowed:
|
|
|
|
In other words:
|
BankAccount a; CheckingAccount b = new CheckingAccount( .... ); a = b; // Upcasting CheckingAccount c; c = a; // *** results in compile error c = (CheckingAccount) a; // Must use casting operator |