• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Object type casting

 
Ranch Hand
Posts: 215
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use tags to post your code.
 
Brij Garg
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic