Please bear(if you feel it is silly) my question nad help in understanding the concept. I have the following code.
class Dog extends Animal
When i say
Dog dog = (Dog) new Animal();
I get a run time(class cast exception) exception. Why is this not caught by compiler ? After all, Animal instance doesn't pass "is A" relationship with Dog(though Dog instance passes "is A" relationship with Animal and hence Animal aniDog = new Dog() works). I am still in infancy stages in java. Guys help me.
Operations cast type implement in run time. hence compiler can not check this mistake in compile time.
Well, what you are getting confused with is actually called upcasting and downcasting in Java.
Here are a couple of links that explain these concepts in really good manner. Have a look at them,
Casting Reference Variables
Hope that helps,
I dont see why you even have a a parent class for this, considering you're overriding its only method. You would be better off having Animal as an interface.
That aside, change it to:
Animal dog = new Dog();
as to reference type casting, such as class casting, JAVA compiler doesn't check it at compile time, it assumes that you know the casting is safe as you did so, so even you cast the Dog object to an String type, it also will not complaint. but at runtime the casting causes an error, because their memories are different. Hope to help
The compiler checks up-casts and it leaves down-casts to the runtime.
Originally Posted by steven.ye
Thanka a million Goldest !!! Very helpful !
Originally Posted by goldest