Casting

Casting

Upcasting

In upcasting, we cannot access from bottom level to top level, but we can access from top level to bottom level. Upcasting is used to convert an object, method or variable of the super class to an object, method or variable of the sub class. Upcasting simply means giving a sub class object to a super class variable.

Figure 1: Upcasting Example

In inheritance, the things in the super class are also owned by the sub class. Therefore, the constructor of the super class also runs in the sub class. So the sub class can access the constructor of the super class. Also, the constructor is called when the object is created. Therefore, when the object of the super class is created, the constructor of the super class is called. Since the sub class can access the constructor of the super class, the sub class can be accessed at the time of creating the object of the super class.

Downcasting

Turning the sub class object into a super class variable back into a sub class object is downcasting. Downcasting simply means passing a super class variable to a sub class object using the sub class object as a parameter.

Figure 2: Downcasting Example

As mentioned in upcasting, the sub class object can be accessed by the super class constructor, so when the sub class object runs, the super class object also runs. So, the subclass object as parameter returns the superclass object as output.

Comments

Popular posts from this blog

Polymorphism

Java Standards, Class & Object

Super Keyword