1
class Animal { 
    public String noise() { 
        return "peep"; 
    }
}
class Dog extends Animal {
    public String noise() { 
        return "bark"; 
    }
}
class Cat extends Animal {
    public String noise() { 
         return "meow"; 
    }
}
class jk{
    public static void main(String args[]){ 
        Animal animal = new Dog();
        Cat cat = (Cat)animal;//line 23
        System.out.println(cat.noise());
    }
}

when i compile this code it shows ClassCastException at line 23. I am not able to understand what the problem is. HELP !!

vandale
  • 3,600
  • 3
  • 22
  • 39
rick
  • 913
  • 6
  • 13
  • 28

2 Answers2

1

A ClassCastException is thrown by the JVM when an object is cast to a data type that the object is not an instance of.

For example

//Compile Error
Integer x = new Integer(10);
String y = (String) x;

//OK
Object x = new Integer(10);
String y = (String) x;

To Avoid ClassCastException you can use instanceof

Object x = new Integer(10);
 if(x instanceof String)
 {
 String y = (String) x;
 }

I hope you will understnad. Thank you.

T8Z
  • 691
  • 7
  • 17
1

The problem is you are trying to type cast a more specific class to a less specific one. More simply, A cat or A dog can be an animal so you can declare dogs and cats as animals as follows:

Animal cat = new Cat();
Animal dog = new Dog();

however you can not refer to an animal as a cat or a dog so the following declarations are invalid

Cat cat = new Animal();
Dog dog = new Animal();
Cat cat = new Dog();
Dog dog = new Cat();

The reason for that is very simple and that's because a more specific class in this case like the cat or dog might have more methods/instance variables that are not present in the more general case. Animal should have the attributes and methods common to all animals but a cat or a dog might do something that's not available to all animals.

In a nut shell you cannot refer to super class object with a subclass reference.

Thresh
  • 470
  • 6
  • 18