explicit casting
Dear Sir,
I cannot getting output using Explicit casting.
Pls explain it. Pls correct this program using Explicit casting.
Explicit Casting
if we write a code which is something like this:
Car Ferrari = Obj;
Here we will get a compile-time error as Obj is not known to the Compiler. Here, we can avoid this error by telling the compiler that we will use Obj as Car by Explicit Casting. This is how we do it:
Car Ferrari = (Car) Obj;
/*sample program*/
class Car {
void Details( )
{
System.out.println("This prints the Car details");
}
}
class Ferrari extends Car {
void Details( )
{
System.out.println("This prints the Ferrari details");
}
}
class BMW extends Car {
void Details( )
{
System.out.println("This prints the BMW details");
}
}
class InheritanceObjectPgm {
public static void main(String[] args) {
Car Ferrari = (Car) Obj;
}
}
Error
InheritanceObjectPgm.java:32: cannot find symbol
symbol : variable Obj
location: class InheritanceObjectPgm
Car Ferrari = (Car) Obj;
^
1 error
class InheritanceObjectPgm {
public static void main(String[] args) {
Object Obj;
Car Ferrari = (Car) Obj;
}
}
Error
InheritanceObjectPgm.java:33: variable Obj might not have been initialized
Car Ferrari = (Car) Obj;
^
1 error
class InheritanceObjectPgm {
public static void main(String[] args) {
Car Obj = new Car();
Car Ferrari = (Car) Obj;
Obj.Details();
}
}
No Error
Output is
This prints the Car details
//but here Obj not call Ferrari Details class.
/*Above no need of writing Car Ferrari = (Car) Obj;
Because Car Ferrari = Obj; it compiles no errors;
But Obj not call Ferrari class by this code.
class InheritanceObjectPgm {
public static void main(String[] args) {
Car Obj = new Car();
Car Ferrari = Obj;
Obj.Details();
}
}
No Error
Output is
This prints the Car details