aspose file tools*
The moose likes Java in General and the fly likes Object type casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Object type casting" Watch "Object type casting" New topic
Author

Object type casting

Rahul Ba
Ranch Hand

Joined: Oct 01, 2008
Posts: 205

Hi, I am unable to understand the term Object typecasting. Whatever I understood, I am depicting here...Please take a look. I am not sure whether Am I correct or not?

Let see we have Car as superclass...

public class Car{
}

public class Ford extends Car{

public String fordMethod(){
return "Ford Method.";
}

}


public class Honda extends Car{

public String hondaMethod(){
return "Honda Method.";
}
}

Now, I have client program as:

public class Client {
public static void main(String[] args) {
Car car = new Car();
Ford ford = (Ford)car;
System.out.println("Ford:"+ford.fordMethod());
}
}

Here I am getting exception as:
Exception in thread "main" java.lang.ClassCastException: com.src.Car incompatible with com.src.Ford
at com.src.Client.main(Client.java:6)

As per my understanding we should not get this exception.
Please explain me object typecasting with this example.

Rahul
Brij Garg
Ranch Hand

Joined: Apr 29, 2008
Posts: 234
Please use tags to post your code.
Brij Garg
Ranch Hand

Joined: Apr 29, 2008
Posts: 234

Car car = new Car();
Ford ford = (Ford)car;


If you will have

then you will not get this exception.
I hope now typecasting is clear to you.

Car is not a Ford so you can not typecast car object to ford.
The typecastng you have done above is called explicit typecasting.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Object type casting