আপকাস্টিং ডাউনকাস্টিং | Object Oriented Programming

আপকাস্টিং ডাউনকাস্টিং ক্লাসটি পলিটেকনিক (Polytechnic) এর অবজেক্ট ওরিয়েন্টেড প্রোগ্রামিং (বিষয় কোডঃ ৬৬৬৪১) (Object Oriented Programming Code 66641) বিষয় এর অংশ।

 

আপকাস্টিং ডাউনকাস্টিং

 

Casting Means Converting One Type to Another Type.

আপকাস্টিং ডাউনকাস্টিং

In java we have two types of castings :

 

1. Upcasting

2. DownCasting

Now let’s first understand the definitions:

1. Upcasting:

Assigning child class object to parent class reference.

Syntax for up casting : Parent p = new Child();

Here p is a parent class reference but points to the child object.

This reference p can access all the methods and variables of the parent class but only overridden methods in the child class.

Upcasting gives us the flexibility to access the parent class members, but it is not possible to access all the child class members using this feature. Instead of all the members, we can access some specified members of the child class. For instance, we can only access the overridden methods in the child class.

2. Downcasting:

Assigning parent class reference (which is pointing to child class object) to child class reference.

Syntax for down casting : Child c = (Child)p;

Here is pointing to the object of the child class as we saw earlier in the example and now we cast this reference p to child class reference c.

Now this child class reference c can access all the methods and variables of the child class as well as the parent class.

For example, if we have two classes, say Machine and Laptop which extends Machine class. Now for upcasting, every laptop will be a machine but for downcasting, every machine may not be a laptop because there may be some machines which can be PrinterMobileetc.

Hence downcasting is not always safe, and we explicitly write the class names before doing downcasting. So that it won’t give an error at compile time but it may throw ClassCastExcpetion at run time, if the parent class reference is not pointing to the appropriate child class.

Let’s see the below example to understand this :

Machine machine = new Machine ();
Laptop laptop = (Laptop)machine;//this won't give an error while compiling
//laptop is a reference of type Laptop and machine is a reference 
//of type Machine and points to Machine class Object .
//So logically assigning machine to laptop is invalid 
//because these two classes have different object strucure.
//And hence throws ClassCastException at run time .

To get rid of ClassCastException we can use instanceof operator to check right type of class reference in case of down casting .

For example,

if(machine instanceof Laptop){
    Laptop laptop = machine;
    //here machine must be pointing to Laptop class object .
}

I’ve tried to explain the upcasting and downcasting use cases with examples. Try to understand the program and read the comments for a complete explanation.

আপকাস্টিং ডাউনকাস্টিং এর বিস্তারিত ঃ

Leave a Comment