Class casting in java

早过忘川 提交于 2019-12-11 11:04:48

问题


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

回答1:


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




回答2:


 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().




回答3:


   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.




回答4:


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.




回答5:


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


来源:https://stackoverflow.com/questions/19291122/class-casting-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!