Explanation of “ClassCastException” in Java

前端 未结 12 1662
小蘑菇
小蘑菇 2020-11-21 11:12

I read some articles written on \"ClassCastException\", but I couldn\'t get a good idea on that. Is there a good article or what would be a brief explanation?

相关标签:
12条回答
  • 2020-11-21 11:44

    It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.

    Let's think of a collection of classes.

    class A {...}
    class B extends A {...}
    class C extends A {...}
    
    1. You can cast any of these things to Object, because all Java classes inherit from Object.
    2. You can cast either B or C to A, because they're both "kinds of" A
    3. You can cast a reference to an A object to B only if the real object is a B.
    4. You can't cast a B to a C even though they're both A's.
    0 讨论(0)
  • 2020-11-21 11:46

    Straight from the API Specifications for the ClassCastException:

    Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

    So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.

    Object i = Integer.valueOf(42);
    String s = (String)i;            // ClassCastException thrown here.
    
    0 讨论(0)
  • 2020-11-21 11:46

    You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.

    But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.

    0 讨论(0)
  • 2020-11-21 11:46

    If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException For example

    class Animal{
       int age;
       String type;
    
       public Animal(int age, String type){
          this.age = age;
          this.type = type;
       }
    }
    public class MainCls{
       public static void main(String[] args){
           Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
           Arrays.sort(arr);
       }
    }
    

    Above main method will throw below runtime class cast exception

    Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable

    0 讨论(0)
  • 2020-11-21 11:48

    A very good example that I can give you for classcastException in Java is while using "Collection"

    List list = new ArrayList();
    list.add("Java");
    list.add(new Integer(5));
    
    for(Object obj:list) {
        String str = (String)obj;
    }
    

    This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.

    0 讨论(0)
  • 2020-11-21 11:51

    It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.

    Consider this heirarchy:

    Object -> Animal -> Dog

    You might have a method called:

     public void manipulate(Object o) {
         Dog d = (Dog) o;
     }
    

    If called with this code:

     Animal a = new Animal();
     manipulate(a);
    

    It will compile just fine, but at runtime you will get a ClassCastException because o was in fact an Animal, not a Dog.

    In later versions of Java you do get a compiler warning unless you do:

     Dog d;
     if(o instanceof Dog) {
         d = (Dog) o;
     } else {
         //what you need to do if not
     }
    
    0 讨论(0)
提交回复
热议问题