What is Upcasting and Downcasting in Java
What is Up Casting and Down Casting in Java,in this article i will step through a sample program and explain when you need to use Up casting and when you need to use Down casting .
In this Sample Program i have created 3 Class
- robot class -> Which is the super Class
- terminator_X_1 -> Which is the Child Class inherit the robot Class
- acessBot Class -> Which Access the robot and terminator_X_1 class
What is Up casting ?
Up Casting is used , when we want to access Function or information in the Super Class. In this Case the Super Class is robot
What is Down Casting ?
Down Casting is used , when we want to access specific behavior in the child Class.
Robot Class
package updowncast; public class robot { public void start(){ System.out.println("Robot Start"); } public void recalibrate(){ System.out.println("Robot recalibrate"); } public void move (){ System.out.println("Robot Moving"); } }
Terminator_X_1 Class
package updowncast; public class terminator_X_1 extends robot { public void start(){ System.out.println("Robot Start"); } public void shooting(){ System.out.println("Terminator is Shooting"); } }
accessBot Class
package updowncast; public class acessBot { public static void main(String[] args) { // TODO Auto-generated method stub //robot robot_1 = new robot(); terminator_X_1 Arnold = new terminator_X_1(); //Up casting robot robot_1 = Arnold; robot_1.recalibrate(); // Down Casting robot robot_2 = new terminator_X_1(); terminator_X_1 genesis = (terminator_X_1)robot_2; genesis.shooting(); } }
Program Explanation
- First , I have created a super class called Robot .
- In the Robot Class i have created 3 Method start() recalibrate () move()
- Then i created the child class terminator_X_1 which inherit the robot super class
- In the terminator_X_1 class i have created 2 Method start() and shoot()
- Then I have created a class called accessBot to access the robot and terminator_X_1 class
- Up casting
- I created a new terminator_X_1 called Arnold
- I cast Arnold into the new robot Object robot_2
- Then I access the robot class recalibrate() to re calibrate Arnold
- Why is that so ?
- You donot want Arnold to access / and know how to recalibrate himself right!!
- Down Casting
- Then i created an object called robot_2
- robot_2 is a new terminator_X_1
- terminator_X_1 genesis = (terminator_X_1)robot_2; this statement is asking ? So now robot_2 is a terminator_X_1 type and your new terminator_X_1 object is named genesis
- /lastly i access the terminator_X_1 method ” genesis.shooting()
Chcek out Numerical Casting in Java here
Leave a Reply