I have the following code:
class A {
}
class B extends A {
public void fB(){};
}
According to Java rule:
Case 1:
Why case 1 is OK and case 2 is not OK: Because a Dog
is an Animal
, but not every Animal
is a Dog
.
class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
Dog fifi = new Dog();
Cat tommy = new Cat();
// OK because Dogs and Cats are Animals
Animal pet1 = fifi;
Animal pet2 = tommy;
// Not OK because an Animal is not always a Dog
Dog doggy = pet2;
Note that casting does nothing to the object; in particular, it doesn't do any kind conversion of objects. Casting is only telling the compiler "I have this object here, and I know better than you what it is; I want you to treat it as type X and not give me any error messages".
So in a line like this:
Dog doggy = pet2;
the compiler will complain because it cannot be sure that pet2
is actually a Dog
; it only knows that it is an Animal
- and not all Animal
s are Dog
s. You can do a cast to tell the compiler to not complain about this:
// Tell the compiler that you want it to treat pet2 as a Dog
Dog doggy = (Dog)pet2;
But when you run the program, Java will still check if pet2
is really a Dog
, and if it isn't, you get a ClassCastException
.
(And the question in your title is exactly the opposite of what you mean, as biziclop noticed).