Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object type casting

 
Rahul Ba
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use tags to post your code.
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic