Why reference variable of type object must be cast when used as other object type

前端 未结 4 1212
一向
一向 2021-01-03 12:08

Although all classes in Java are sub-classes of Object class, but different from other object types, a reference variable of type Object can\'t be assigned to any other refe

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-03 12:47

    you wanna know why we use explicit type cast. this is all about Inheritance -

    Let me clear this - Let suppose we have two class Class A and Class B. And Class B is a sub class of class A. That means Class B has all functionality of Class A, this means Class B can do anything what Class A can do. So if

     A a = new B();
    

    is perfectly fine because Class B can do what class A can do. Here reference varaible a is of type Class A, from a all the method of Class A will be invokable.Now Object of B(new B();) has all the functionality of Class A (as Inheritance) so all method of Class A will be invokable.

    If we reverse the condition like this ->

          B b =new A();
    

    Not possible, because may be Class B implement its own functionality(Methods and variables) which are not in Class A. But here reference variable is of type B, all the functionality of Class B will be invokable, But the actual object is of type A so Error will occur.

    Same case is with Class Object.As all the other Class automatically inherit Object Class.

    so When any object having reference variable of type Class Object need explicit Cast, Because this is not sure what more or less functionality that object contain.

提交回复
热议问题