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 !!

4
  • 2
    Dogs can never be cats. Seems legit. But in extreme cases, the opposite can be done. Commented Mar 9, 2014 at 16:12
  • Dogs and Cats are not in same inheritance hierarchy. Commented Mar 9, 2014 at 16:13
  • Dog and Cat class are separate. they dont have any relationship in terms of inheritance.. Commented Mar 9, 2014 at 16:23
  • possible duplicate of ClassCastException Commented Mar 9, 2014 at 16:29

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.