Object Oriented Programming - JAVA- Casting

Object Oriented Programming - JAVA👽

Casting ......

We use casting to catch a class using another class. So in this blog we discuss about Casting.
 
  
What's going on in Casting  ? In casting, we have to inherit classes.
Let's see an example.
    int x  = 5 ;    Integer variables have 32 bits.
   long y = 6 ;    Long variables have 64 bits.
       x = y ; ✖    We can't catch long variable using integer variable.
   y = x ; âœ”    We can catch integer variable using long variable.

There are two types of casting.
  • Upcasting
  • Downcasting

Upcasting

    Upcasting is a process of assign subclass object to superclass variable that is reference of superclass. 

class Parent {
    //code
}
class Child extends Parent {
    //code
}
class Test {
    Parent p = new Child();
}
The object always runs in the class where the object is created. So, in upcasting, always run the subclass.

Downcasting

    Downcasting is a process of converting subclass object assigned to a variable with a subclass reference back into a subclass variable.

class Parent {
    //code
}
class Child extends Parent {
    //code
}
class Test {
    Parent p = new Child();
    Child c = (Child) p ;
}

We can downcasting only when we done upcasting process. 

See you in the next blog to discuss about Polymorphism.


Comments

Popular posts from this blog

Application Programming Interface (API)

Design Patterns

Behavioral Design Pattern - Software Engineering