开发者

OOP basics of how objects are created

Following oo situation:

class A{
    开发者_高级运维    public A(){ System.out.println("Regular constructor of A"); }
        public A(int i){ System.out.println("Constructor of A with " + i); }
    }

    class B extends A{
        public B(){
            super(3);
            System.out.println("Regular constructor of B");
        }
        public B(int i){ System.out.println("Constructor of B with " + i); }
    }

I am practicing oo programming. What happens if I initiate an object this way?

B b1 = (B) new A();

However such a type cast doesn't make sense to me. What would be the output? Please describe why.


The output will be an exception when you try to cast to B, like this:

Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B
    at Test.main(Test.java:16)

An instance of "just an A" isn't an instance of B, which is why the cast fails.

Now you could do this:

A a = new B();
B b = (B) a; // No exception!

because in that case although the type of the a variable is just A, its value refers to an instance of B... so the cast succeeds.


ClassCastException

B extends A

You can not cast A to B because A is not B

(B) A // class cast exception

with the same logic B is A so

(A) B // true
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜