简体   繁体   中英

Java Downcasting/Upcasting

I am getting ClassCastEception in the following code. Me class extends the person class. why can't i downcast the Me object to Person. I can't understand the logic here. please anyone make me clear with good explanation.

public class Conv {

    public class Person {
        public void setName(String name) {
            this.name = name;
        }
        public String name = "X";
        public Person(String n) {
            name = n;
        }
        /*
         * many other variables and procedures
         */
    }

    public class Me extends Person {
        /*
         * nothing more in this class
         */
        public Me(String n) {
            super(n);
        }
    }
    public void test() {
        Person p = new Person("Roy");
        Me a = (Me) p;
        System.out.println(a.name);
    }

    public static void main(String[] args) {
        new Conv().test();
    }
}

Every Cat is an Animal. But not every Animal is a Cat. Same rule applies here. You cannot turn every Person to Me . Where as every Me is a Person .

You are creating p as new Person , not new Me . For casting, it's the runtime type that is checked. If you create Person p = new Me("Roy") , then you can cast it to Me because in reality (during runtime) even though it's declared as Person , it is a Me .

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