Forum : explicit casting
Brief description  about Online courses   join in Online courses
View Rintu  M  A 's Profile

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




Asked by Rintu M A | Sep 8, 2010 |  Reply now
Replies (2)
View rintu m--a 's Profile
but sir, again i got error.. pls correct sir...

//in the main class
class InheritanceObjectPgm {
public static void main(String[] args) {
Object Obj = new Ferrari();
Car Ferrari = (Car) Obj;
Obj.Details();
}
}

InheritanceObjectPgm.java:34: cannot find symbol
symbol : method Details()
location: class java.lang.Object
Obj.Details();
^
1 error
Sep 13, 2010
View arun kumar das 's Profile
Hi Rintu,

The Problem here is that you have not specified anything about Obj variable here. The compiler doesn't know if Obj is an Object or not. To let the compiler know this we have to modify the main class as mentioned below:

class InheritanceObjectPgm {

public static void main(String[] args) {
Object Obj = new Ferrari();
Car Ferrari = (Car) Obj;
}

Regards,
Java Teacher
Sep 13, 2010