简体   繁体   中英

Class casting in java

In my code two classes are there ,subclass extends superclass.In sub class i override superclass method. On the time of object creation i created superclass reference to sub class object its working fine. But again i converted super class reference to complete super class object but it calls sub class methodn not super class method. My assumption the output is wrong.Here my code

public class OverRiding {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //Super class reference to sub class Object
        Dog dog = new Animal();
        dog.eat();
        dog.bow();

        //Completely converted into pure Dog class Object
        Dog d = (Dog) dog;
        d.eat();
        d.bow();
    }
}

Dog class

class Dog {
    public void eat() {
        System.out.println("Dog eat Biscuits");
    }

    public void bow() {
        System.out.println("Dog bow");
    }
}

Class Animal

class Animal extends Dog {
    public void eat() {
        System.out.println("Animal eat Food");
    }
}

And my output is

Animal eat Food
Dog bow
Animal eat Food
Dog bow

Your concept is not correct bro...

 class Animal extends Dog

How can Animal extend a dog? . Its like saying - "EVERY ANIMAL IS A DOG" . Which is wrong... So, it should be the other way around...

This example will only confuse you further..

Donno why nobody brought this up...

 Dog d = (Dog) dog;

Here d is not pure Dog object. It's still of Animal type. Pure Dog object would be created via Dog d = new Dog() .

   Dog dog = new Animal();
    //Completely converted into pure Dog class Object
    Dog d = (Dog) dog;

Both Dog and d are pointing to the same reference, Since you are not creating a new object . Cast won't have an effect here.

Casting and Creating is completely different.

In this example, you've only created one object, and it's an Animal , (which sadly, is a special type of Dog ). When you call eat on this object, you're always going to get the version defined in the Animal class, not the version defined in the Dog class.

That's polymorphism. The version of the method that gets called depends on the class of the object, not the type of the variable that refers to it.

You assumption is false:

Completely converted into pure Dog class Object

When you are casting your Animal to a Dog , your variable d is still an Animal . It is also a Dog , but the most specific type is Animal .

You are not completely converted your variable to another instance. Your instance is still the same.

For a proof, you can try this code :

Dog d = (Dog) dog;
d.getClass(); // output Animal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM