What is the difference between up-casting and down-casting with respect to class variable

后端 未结 10 1753
暗喜
暗喜 2020-11-22 09:55

What is the difference between up-casting and down-casting with respect to class variable?

For example in the following program class Animal contains only one method

10条回答
  •  不思量自难忘°
    2020-11-22 10:02

    Parent: Car
    Child: Figo
    Car c1 = new Figo();

    =====
    Upcasting:-
    Method: Object c1 will refer to Methods of Class (Figo - Method must be overridden) because class "Figo" is specified with "new".
    Instance Variable: Object c1 will refer to instance variable of Declaration Class ("Car").

    When Declaration class is parent and object is created of child then implicit casting happens which is "Upcasting".

    ======
    Downcasting:-
    Figo f1 = (Figo) c1; //
    Method: Object f1 will refer to Method of Class (figo) as initial object c1 is created with class "Figo". but once down casting is done, methods which are only present in class "Figo" can also be referred by variable f1.
    Instance Variable: Object f1 will not refer to instance variable of Declaration class of object c1 (declaration class for c1 is CAR) but with down casting it will refer to instance variables of class Figo.

    ======
    Use: When Object is of Child Class and declaration class is Parent and Child class wants to access Instance variable of it's own class and not of parent class then it can be done with "Downcasting".

提交回复
热议问题