REFERENCE VARIABLE CASTING

class Animal
{
void animalfun(){System.out.println("this is fun method of animal");};
};
class Dog extends Animal
{
void dogfun(){System.out.println("this is the hi method of dog");}
};

We know how to pass subclass reference to supercast in exception,
like- Animal animal=new Dog();//this is known as upcasting
But the problem is here we can not call the sub-class(Dog) method (legs()) through the instance 'animal'.
So we have to type cast(down cast) like
Dog dog=(Dog)animal;

We should write the code like this

class Animal
{
void animalfun(){System.out.println("this is fun method of animal");};
};
class Dog extends Animal
{
void dogfun(){System.out.println("this is the hi method of dog");}
};
class demo
{
public static void main(String[] args){
Animal animal=new Dog();
Dog dog=(Dog)animal;
dog.animalfun();
dog.dogfun();
}};


the two lines
Dog dog=(Dog)animal;
dog.dogfun();
can be combined to
((Dog)animal).dogfun();
Now the dog instance can call both the methods of Animal and Dog.
The new and improved code block contains a cast, which in this case is
sometimes called a downcast, because we're casting down the inheritance tree to a
more specific class.
Before we try to invoke the mothod,we cast the animal variable to type Dog.
What we're saying to the compiler is, "We know it's really referring to a Dog object, so it's okay to make a new Dog reference variable to refer to that object."

It's important to know that the compiler is forced to trust us when we do a
downcast, even when we screw up:
class Animal { }
class Dog extends Animal { }
class Demo {
public static void main(String [] args) {
Animal animal = new Animal();//we have to give the sub-class reference in this line
Dog d = (Dog) animal; // compiles but fails later(runtime exception)
}}

This code compiles! When we try to run it, we'll get an exception something like this: java.lang.ClassCastException

Why can't we trust the compiler to help us out here? Can't it see that animal
is of type Animal? All the compiler can do is verify that the two types are in the
same inheritance tree, so that depending on whatever code might have come before
the downcast, it's possible that animal is of type Dog. The compiler must allow things that might possibly work at runtime. However, if the compiler knows with
certainty that the cast could not possibly work, compilation will fail.

The following replacement code block will NOT compile:

Animal animal = new Animal();
Dog d = (Dog) animal;
String s = (String) animal;
// animal can't EVER be a String

In this case, you'll get an error something like this:
inconvertible types

No comments:

Post a Comment