|
|
(ClassB) x // x contains a value of type ClassA |
y = (ClassB) x; // x contains a value of type ClassA |
|
|
|
How to compile the program:
|
You will see the following error messages:
Demo.java:8: inconvertible types found : ClassB required: ClassA x = (ClassA) y; ^ Demo.java:9: inconvertible types found : ClassA required: ClassB y = (ClassB) x; ^ 2 errors |
|
Example:
|
|
|
|
Example:
public class ClassA public class ClassB extends ClassA { { ... ... } } |
|
Example:
public class ClassA public class ClassB extends ClassA { { ... ... } } |
base class (parent class) - parent preceeds any child ^ | | | upcasting | | downcasting | v derived class (child class) |
How to compile the program:
|
Notes:
|
|
|
public class ClassA public class ClassB extends ClassA { { ... var1; // Receives ALL variables and methods ... var2; // defined in ClassA } ... var3; ... var4; } |
var1 var2 (Because a is of type ClassA and ClassA has the variable var1 and var2) |
Now the variable a is pointing to a ClassB object:
Notice that:
|
|
int b = 3; double a; a = b; // You do not need to use a = (double) b; |
|
Example with primitive types:
int b = 3; double a; a = b; // Conversin of int ⇒ double is safe. // Java performs this automatic conversion: // a = (double) b; |
Example with user-defined types:
ClassB b = new ClassB(); // ClassB is a derived class of ClassA ClassA a; a = b; // Conversin of ClassB ⇒ ClassA is safe. // Java performs this automatic conversion: // a = (ClassA) b; |
How to compile the program:
|
Notes:
|
public class ClassA public class ClassB extends ClassA { { ... var1; // Receives ALL variables and methods ... var2; // defined in ClassA } ... var3; ... var4; } |
var1 var2 var3 var4 (Because b is of type ClassB and ClassB has all 4 variables) |
Now the variable b is pointing to a ClassA object:
Notice that:
|
|
Example:
public class ClassA public class ClassB extends ClassA { { ... var1; // Receives ALL variables and methods ... var2; // defined in ClassA } ... var3; ... var4; } |
How to compile the program:
|
Notes:
|
|
Common mistake:
|
Example:
public class ClassA public class ClassB extends ClassA { { ... var1; // Receives ALL variables and methods ... var2; // defined in ClassA } ... var3; ... var4; } |
Result:
|
How to compile the program:
|
Notes:
|