Java convert to child class

Upcasting Vs Downcasting in Java

Typecasting is one of the most important concepts which basically deals with the conversion of one data type to another datatype implicitly or explicitly. In this article, the concept of typecasting for objects is discussed.
Just like the data types, the objects can also be typecasted. However, in objects, there are only two types of objects, i.e. parent object and child object. Therefore, typecasting of objects basically means that one type of object (i.e.) child or parent to another. There are two types of typecasting. They are:

  1. Upcasting: Upcasting is the typecastingof a child object to a parent object. Upcasting can be done implicitly. 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 access the overridden methods.
  2. Downcasting: Similarly, downcasting means the typecasting of a parent object to a child object. Downcasting cannot be implicit.

The following image illustrates the concept of upcasting and downcasting:

Example: Let there be a parent class. There can be many children of a parent. Let’s take one of the children into consideration. The child inherits the properties of the parent. Therefore, there is an “is-a” relationship between the child and parent. Therefore, the child can be implicitly upcasted to the parent. However, a parent may or may not inherits the child’s properties. However, we can forcefully cast a parent to a child which is known as downcasting. After we define this type of casting explicitly, the compiler checks in the background if this type of casting is possible or not. If it’s not possible, the compiler throws a ClassCastException.
Let’s understand the following code to understand the difference:

Источник

How to cast parent into child in java?

In Java, it is possible to cast a parent object to its child object, but it is not always valid and may result in a runtime error called ClassCastException. This occurs when the object being cast is not actually an instance of the target class or its subclasses. In order to avoid this error, it is important to properly check the type of the object before attempting to cast it. In this article, we will explore two methods for casting a parent object to its child in Java.

Method 1: Using instanceof operator

To cast a parent object into a child object in Java using the instanceof operator, you can follow these steps:

class Parent  // parent class code > class Child extends Parent  // child class code >
Parent parentObj = new Parent();
if (parentObj instanceof Child)  // parent object is an instance of Child class >
Child childObj = (Child) parentObj;

Here is an example code that demonstrates the above steps:

class Parent  public void parentMethod()  System.out.println("Parent method called"); > > class Child extends Parent  public void childMethod()  System.out.println("Child method called"); > > public class Main  public static void main(String[] args)  // create parent object Parent parentObj = new Parent(); // check if parent object is an instance of Child class if (parentObj instanceof Child)  // parent object is an instance of Child class Child childObj = (Child) parentObj; childObj.childMethod(); > else  System.out.println("Parent object is not an instance of Child class"); > // create child object Child childObj2 = new Child(); // cast child object to parent object Parent parentObj2 = childObj2; // call parent method parentObj2.parentMethod(); // check if parent object is an instance of Child class if (parentObj2 instanceof Child)  // parent object is an instance of Child class Child childObj3 = (Child) parentObj2; childObj3.childMethod(); > else  System.out.println("Parent object is not an instance of Child class"); > > >

In the above code, we first create a parent object and check if it is an instance of the child class using the instanceof operator. Since it is not an instance of the child class, we print a message saying so.

Next, we create a child object and cast it to a parent object. We then call a method on the parent object, which is a method of the parent class.

Finally, we check if the parent object is an instance of the child class using the instanceof operator. Since it is an instance of the child class, we cast it to a child object and call a method on it that is specific to the child class.

Method 2: Using Class.isInstance() method

To cast a parent object into a child object in Java using the Class.isInstance() method, you can follow these steps:

Parent parentObj = new Parent();
  1. Now, you can use the Class.isInstance() method to check if the parent object can be cast into a child object:
if (Child.class.isInstance(parentObj))  childObj = (Child) parentObj; >
  1. If the Class.isInstance() method returns true , you can safely cast the parent object into a child object using the (Child) cast operator.

Here is the complete code:

class Parent  // Parent class implementation > class Child extends Parent  // Child class implementation > public class Main  public static void main(String[] args)  Parent parentObj = new Parent(); Child childObj; if (Child.class.isInstance(parentObj))  childObj = (Child) parentObj; // Do something with childObj > > >

In this example, the Child class extends the Parent class, so a Child object is also a Parent object. The Class.isInstance() method checks if the parentObj instance is an instance of the Child class, and if so, it casts the parentObj to a Child object using the (Child) cast operator.

Note that if the Class.isInstance() method returns false , the cast operation will result in a ClassCastException . Therefore, it is important to always check the result of the Class.isInstance() method before casting the object.

Источник

Java Type Casting (Downcasting, Upcasting)

Typecasting is the process of conversion of the type of data. Object Typecasting can be of two types, depending on whether we are converting from parent type to child or going in the other way. In this tutorial, we will learn about Upcasting and Downcasting of objects in Java.

Upcasting and Downcasting in Java

Upcasting

  • The process of casting an object of child class to the parent class is called Upcasting.
  • Upcasting can be done implicitly or explicitly.
  • Upcasting will reduce the choice of methods, we can use on the typecasted object.
  • However, for overridden methods, static or dynamic binding comes into play, and it will decide the method implementation to use.

To demonstrate upcasting, we will use a child and a parent class. The child class has an overridden print() method and a printName() method. The following code shows the implementation.

class SuperClass < public void print() < System.out.println("Printing from SuperClass"); >> class Child extends SuperClass < String name; Child(String s) < this.name = s; >@Override public void print() < System.out.println("Printing from Child class"); >public void printName() < System.out.println(this.name); >>

Implicit Upcasting

When we assign an object of the Child class to a reference variable of SuperClass type, then implicit upcasting takes place. We can use the print() method on this object, and the method implementation of the Child class will be used.

public static void main(String[] args) < Child c = new Child("child"); c.print(); //Implicit Upcasting SuperClass s2 = new Child("Second Child"); s2.print();//print() method of Child class is called due to dynamic binding >

Printing from Child class
Printing from Child class

Another example of implicit upcasting is shown below. If we create an ArrayList of SuperClass type and add child classes objects to it, then they are implicitly upcasted to the SuperClass. We also created a new class(AnotherChild).

import java.util.ArrayList; class AnotherChild extends SuperClass < public void print() < System.out.println("Printing from AnotherChild class"); >> public class TypeCastingDemo < public static void main(String[] args) < SuperClass obj1 = new SuperClass(); Child obj2 = new Child("First Child"); AnotherChild obj3 = new AnotherChild(); ArrayListsuperClassList = new ArrayList<>(); superClassList.add(obj1); superClassList.add(obj2); superClassList.add(obj3); for(int i=0; i >

Printing from SuperClass
Printing from Child class
Printing from AnotherChild class

Explicit Upcasting

We can also explicitly cast the object, but it is not really required.

public static void main(String[] args) < Child c = new Child("child"); c.print(); //Explicit Upcasting SuperClass s2 = (SuperClass) new Child("Second Child"); s2.print();//print() method of Child class is called due to dynamic binding >

Printing from Child class
Printing from Child class

Upcasting Narrows the Choice Of Methods

As discussed above, upcasting will narrow our choices of methods. For example, after upcasting a Child class object to SuperClass, we can no longer use the printName() method of the Child class. We will get a compilation error.

public class TypeCastingDemo < public static void main(String[] args) < SuperClass s = new Child("First Child"); s.printName();//Error >>

Exception in thread «main» java.lang.Error: Unresolved compilation problem:
The method printName() is undefined for the type SuperClass

Upcasting with Interfaces

Upcasting also works with interfaces. Let’s create a new interface and implement it in our Child class.

interface Name < public void printName(); >class Child extends SuperClass implements Name < String name; Child(String s) < this.name = s; >@Override public void print() < System.out.println("Printing from Child class"); >public void printName() < System.out.println(this.name); >>

Now, we will create an object of the Child class and assign it to an interface type variable. Implicit typecasting will take place in this case. We can use the implemented printName() method.

public class TypeCastingDemo < public static void main(String[] args) < Name obj = new Child("First Child"); obj.printName(); >>

But we can’t use the overridden print() method.

public class TypeCastingDemo < public static void main(String[] args) < Name obj = new Child("First Child"); obj.print();//Error >>

Exception in thread «main» java.lang.Error: Unresolved compilation problem:
The method print() is undefined for the type Name

Upcasting to Object Class

All classes internally extend the Object class. Object class is the superclass of all other classes. So we can upcast the Child class(or any other class) to the Object class.

public class TypeCastingDemo < public static void main(String[] args) < Object o = new Child("hello"); System.out.print(o.getClass()); >>

Downcasting in Java

  • Downcasting can be considered as the reverse of Upcasting. We are typecasting an object of the parent class to the child class.
  • Unlike upcasting, downcasting is not done implicitly by the compiler.

As we saw in upcasting, the following code gives an error.

public class TypeCastingDemo < public static void main(String[] args) < SuperClass s = new Child("First Child"); s.printName();//Error >>

To make it work, we can downcast from the SuperClass to the Child class. This will give us access to the print() method of the Child class.

public class TypeCastingDemo < public static void main(String[] args) < SuperClass s = new Child("First Child"); ((Child) s ).printName();//Downcasting from SuperClass to Child class. >>

ClassCastException in TypeCasting

The ClassCastException is a commonly encountered exception that occurs when downcasting. The following code demonstrates this error.

We created a new AnotherChild class and in the main() method, we created three objects, one for each class(SuperClass class, Child class, and AnotherChild class), and we are adding them to an ArrayList . Now when we cast each object to the Child class, then we will get this error. This happens because there is no parent-child relationship between the AnotherChild class and the Child class. So we can’t downcast from AnotherChild to Child.

class AnotherChild extends SuperClass < public void print() < System.out.println("Printing from AnotherChild class"); >> public class TypeCastingDemo < public static void main(String[] args) < ArrayListlist = new ArrayList<>(); SuperClass s = new Child("First Child"); Child c1 = new Child("Second Child"); AnotherChild c2 = new AnotherChild(); list.add(s); list.add(c1); list.add(c2); for(int i=0; i > >

First Child
Second Child
Exception in thread «main» java.lang.ClassCastException: class AnotherChild cannot be cast to class Child (AnotherChild and Child are in unnamed module of loader ‘app’)
at TypeCastingDemo.main(TypeCastingDemo.java:57)

We can use the instanceof operator to rectify this error. This operator returns true if the object is of a particular type. We can correct the above code by using the instanceof operator before downcasting.

public class TypeCastingDemo < public static void main(String[] args) < ArrayListlist = new ArrayList<>(); SuperClass s = new Child("First Child"); Child c1 = new Child("Second Child"); AnotherChild c2 = new AnotherChild(); list.add(s); list.add(c1); list.add(c2); for(int i=0; i > >

Using cast() and isInstance() methods

Java provides an alternative way of downcasting. We can use the cast() method to downcast from a superclass to a subclass. Similarly, the isInstance() method can replace the instanceof operator. These two methods are often used together in generic methods. Let’s rewrite the above code using these methods.

public class TypeCastingDemo < public static void main(String[] args) < ArrayListlist = new ArrayList<>(); SuperClass s = new Child("First Child"); Child c1 = new Child("Second Child"); AnotherChild c2 = new AnotherChild(); list.add(s); list.add(c1); list.add(c2); for(int i=0; i > > >

In this tutorial, we learned how to upcast and downcast objects in Java. Upcasting can be done implicitly or explicitly and converts the type from subclass to superclass. It narrows down the methods we can use with the object. Downcasting is the process of casting superclass to subclass. We can only explicitly downcast an object. Downcasting is performed to access the methods and properties of the child class. We must use the instanceof operator or the isInstance() method to downcast safely. It is done to avoid the ClassCastException.

Источник

Читайте также:  Html numbered list css
Оцените статью