Class Type Casting
Casting one type of class to another type of class is known as class type casting. To perform class type casting we have to follow these two rules.
1. Classes must be in " Is-A-Relationship"
2. Object must have the property of class in which it is going to be casted.***
There are two type of casting
a. Up casting: subclass type casting to the super class type. Subclass object referred by super class reference variable . It can be done by two ways implicit and explicit.
Implicit: done by compiler without cast syntax.
Explicit: done by the programmer with cast syntax.
b. Down Casting: super class type casting to the subclass type. The object which is already up casted that object only can be performed down cast here subclass reference variable reference to the super class reference variable with type cast syntax. It always perform explicit.
Note: Without performing up cast if we try to perform down cast. We will get CCE- ClassCastException.
**Note: Up casting and Down casting can be understood better with the example of WhatsApp Group.
1. Example Of Class Type Casting:
class Member{
String name;
long phone;
void chat(){
System.out.println(name+" is chatting in group");
}
}
class Admin extends Member{
void addUser(){
System.out.println(name+" adding a new user in group");
}
}
class UpAndDownCast{
public static void main(String[] args) {
Member mem = new Admin(); // Upcasting acess only general property of super class
mem.name = " Rahul";
mem.phone=9856478562l;
mem.chat();
Admin ad=(Admin)mem; // Down cast to access specific property of subclass
ad.addUser();
}
}
Output.
Rahul is chatting in group
Rahul adding a new user in group
2. Example Of Class Type Casting:
This example is based on two types of students i.e., developer and testers:
class Student{// Example of up and down cast
String name;
int id;
void java(){
System.out.println(name+ " attending java class");
}
}
class DevStudent extends Student{
void advanceJava(){
System.out.println(name+" attending advanceJava class");
}
}
class TestStudent extends Student{
void manual(){
System.out.println(name+" attending manual class");
}
}
class HR{
public static void main(String[] args) {
Student st = new TestStudent(); // Up Cast - new DevStudent();
st.name = "Rahul";
st.id=123;
st.java();
TestStudent ts = (TestStudent)st;
ts.manual();
}
}
Output:
Rahul attending java class
Rahul attending manual class
No comments:
Post a Comment