Upcasting in Java | Code Underscored

0
27

Typecasting transforms one data type into another, and object typecasting includes upcasting and downcasting. The object can also be typecast in Java, just as datatypes. Additionally, there are two kinds of objects: parent and child objects. Parent to Child and Child to Parent, or Upcasting and Downcasting, are the two types of typecasting that can occur for an object.

The object can also be typecast in Java, just as datatypes. There are two kinds of objects: parent and child objects. Parent to Child and Child to Parent, or Upcasting and Downcasting, are the two types of typecasting that can occur for an object.

To check whether variables are handled appropriately by a function, typecasting is employed.

We simultaneously typecast a child object to a parent object and a parent object to a child object in upcasting and downcasting. Upcasting can be done expressly or implicitly, but downcasting is not feasible implicitly.

Let’s explore Upcasting of the object casting in depth in this article!

Upcasting

A type of object typecasting called upcasting involves typecasting a child object to a parent class object. We may access the variables and methods of the parent class in the child class by utilizing upcasting.

Here, we only access a portion of the procedure and variables. Only a few specific child class variables and methods are accessed. Broadening and generalization are other names for upcasting. The Syntax of Upcasting is as follows:

ParentObject po = new ChildObject();

Internal upcasting will take place, and as a result, the object can only access certain members (overridden methods, etc.) of the parent and child classes.

// The subsequent variable is not readily accessible
po.id = 1;

Illustrating the concept of Upcasting in Java

Allow for a parent class. A parent may have several children. Now, take one of the youngsters as an example. The parent’s attributes are passed on to the child. The parent and child, therefore, have an “is-a” relationship. As a result, the parent may be implicitly upcasted to the child. A parent, however, may or may not inherit a child’s possessions. But downcasting, or forcing a parent onto a child, is possible.

After explicitly specifying it, the compiler checks in the background to see if this form of casting is possible. The compiler throws a ClassCastException if it is not feasible. To further explain the idea of ​​Java’s upcasting, let’s examine the following code:

// Upcasting.java

    class  ParentObject  
       void showInfo()   
          System.out.println(" parent's class method");  
         
      
      
    class ChildObject extends ParentObject   
       void showInfo()   
          System.out.println(" child class's method ");  
         
      
    class CodeUpcasting  
       public static void main(String args[])   
            
          ParentObject firstObj = (ParentObject) new ChildObject();  
          ParentObject secondObj = (ParentObject) new ChildObject();
  
          firstObj.showInfo();  
          secondObj.showInfo();  
         
      

Another sort of object typecasting is upcasting. A parent class reference object is given to the child class during upcasting. Although it is impossible to give a parent class reference object to a child class in Java, if downcasting is used, there won’t be any compile-time errors. The “ClassCastException” is thrown when we attempt to run it.

To better understand the use of upcasting in Java, we will employ an example of downcasting to drive the point home. The question is, why does the compiler permit downcasting if it is not possible in Java? In some Java contexts, downcasting is an option. The parent class, in this case, refers to the subclass object. Here is a downcasting example that explains both the legitimate and the illegitimate scenarios:

// Downcasting.java

    // this class belongs to a Parent  
    class ParentObject    
        String name;   
        
        // A method that prints the data of the parent class   
        void displayMessage()   
           
            System.out.println("Parent method is called");   
           
       
        
    // this class belongs to a Child   
    class ChildObject extends ParentObject    
        int age;   
        
        // Performing overriding  
        @Override  
        void displayMessage()   
           
            System.out.println("Child method is called");   
           
       
        
    public class Downcasting  
        
        public static void main(String[] args)   
           
            ParentObject po = new ChildObject();  
            po.name = "Tyson";  
              
            // Performing Downcasting Implicitly   
            //ChildObject c = new ParentObject(); // it gives compile-time error   
              
            // Performing Downcasting Explicitly   
            ChildObject co = (ChildObject)p;   
        
            co.age = 18;   
            System.out.println(co.name);   
            System.out.println(co.age);   
            co.displayMessage ();   
           
      

Why is upcasting necessary in Java?

Upcasting is not frequently used in Java. When writing code that solely affects the parent class, we use it. Downcasting is used when writing code to access the child class’s actions.

What is outstanding about Upcasting

The following are key identities of upcasting in Java, leading to a clearer understanding of the variations between upcasting and downcasting. A parent object receives a typecast of a child object. On the other hand, the parent class object’s reference is supplied to the child class when handling downcasting.

Upcasting can be done explicitly or implicitly. However, it is not feasible to downcast implicitly.

We have access to the parent class’s variables and methods in the child class when upcasting in Java. On the contrary, you can access the parent and child classes’ methods and variables when performing downcasting. In addition, we can only access a few specific child class methods in Java’s upcasting. But by using downcasting, it is possible to access all of the variables and methods of both classes.

The syntax for Java’s upcasting is as follows:

ParentObject po = new ParentObject()

Now, contrast this with Java’s downcasting, which is represented using the following code snippet.

ParentObject po = new ChildObject()
ChildObject co = (ChildObject)po;

Example: Demonstrating the idea of ​​typecasting in general

// This is Java's program  illustrating the variation of  Upcasting and Downcasting

// this class belongs to a parent
class ParentObject 
	String name;

	// this method is responsible for printing the parent class's signature

	void displayMethod()
	
		System.out.println(" Parent class's Method");
	


// Child class
class ChildObject extends ParentObject 
	int id;

	// this method overrides its parent method & subsequently prints the  child class's signature
	@Override void displayMethod()
	
		System.out.println("Method from Child");
	


// this class  demonstrates the differences arising between upcasting and downcasting
public class CUS 

	// The program's driver's code
	public static void main(String[] args)
	
		// Upcasting
		ParentObject po = new ChildObject();
		po.name = "CodeUnderScored";

		//the parent class name being printed
		System.out.println(po.name);

		//Since the parent class function is overridden, we will use this.
		po.displayMethod();

		// making attempts to implicitly downcast
		// ChildObject co = new ParentObject(); - > compile time error

		// Downcasting Explicitly
		ChildObject co = (ChildObject)po;

		co.id = 1;
		System.out.println(co.name);
		System.out.println(co.id);
		co.displayMethod();
	


Conclusion

One of the most crucial ideas is typecasting, which essentially deals with the implicit or explicit conversion of one data type to another. We have explosively covered the idea of ​​upcasting typecasting for objects in this article.

The objects can also be typecasted, just like the data types. There are only two types of objects in objects: parent objects and child objects. Typecasting of objects, then, fundamentally refers to the conversion of one kind of object, such as a child or parent, to another.

Casting a given child object to a parent object is known as upcasting. Implicit upcasting is a possibility. Upcasting allows us the freedom to access the parent class members, but it is impossible to use this feature to access all the child class members. We can access a subset of the child class’s members rather than all. We can, for example, access the overridden methods.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here