Typecasting an Object from Parent Class to Child

Typecasting an object from parent class to child

Once you create an object, you can't change its type. That's why you can't cast an Animal to a Dog.

However, if you create an object of a sub-class, you can keep a reference to it in a variable of the super-class type, and later you can cast it to the sub-class type.

This will work :

Animal a = new Dog ();
Dog d = (Dog) a;

In the Android example, you have a layout resource that looks like this :

<EditText
android:id="@+id/edit_message"
..."/>

This definition will cause Android to create an instance of EditText, and therefore you can cast the view returned by findViewById to EditText. You can't cast it to anything else that isn't a super-type of EditText.

Convert Parent Class to child in java

You are asking if there is a more convenient way to do this. If we consider just copying parameters from one object to another then there is no another way to do this. There might be ways to work around the problem by having objects for groups of member fields or by automating it by code that can copy member fields with same name from object to another.

Small fix

But first, let's improve design a bit. Fields should not be duplicated like this between classes in a class hierarchy. So let's eliminate that duplication:

public class Student {
private String name;
private int roll;

public Student(String name, int roll) {
this.name = name;
this.roll = roll;
}

public String getName() {
return name;
}

public int getRoll() {
return roll;
}
}

public class HonorStudent extends Student {
private int honorId;

public HonorStudent(String name, int roll, int honorId) {
super(name, roll);
this.honorId = honorId;
}

public int getHonorId() {
return honorId;
}
}

Copy constructor

If there is really a need to copy objects then copy constructor can be useful. Creating a copy constructor will allow you to skip passing each member field only by one.

public Student(Student other) {
this.name = other.name;
this.roll = other.roll;
}

Then creating Student part of the HonorStudent becomes simpler

public HonorStudent(Student student, int honorId) {
super(student);
this.honorId = honorId;
}

Design

Now it is not common that objects change their type. So this is not a common thing to do. This is usually solved by different kind of design of classes. For example, honorId could be part of Student class because, I guess, student can gain this attribute or loose it. Behaviour related to honor can be in some other class that is attached to student class.

Reading about behavioural design patterns can be useful. Depending which pattern to choose will depend on the use case and the problem that you are trying to solve.

How to Cast parent class object to child class object?

How to Convert parent class object to child class object?

In your code, you aren't converting anything, you're casting. Casting (the thing you're doing with (B)) just changes the kind of reference you have to an object, it doesn't change the object at all. If the new reference type isn't supported by the object, the cast fails (as you've discovered).

You can't convert an object, but you can create a new object based on another object. It would be possible, for instance, to define a B constructor that accepted an A instance and used information from it as part of the process of initializing a B instance.

How to cast parent into child in Java

Well you could just do :

Parent p = new Child();
// do whatever
Child c = (Child)p;

Or if you have to start with a pure Parent object you could consider having a constructor in your parent class and calling :

class Child{
public Child(Parent p){
super(p);
}
}
class Parent{
public Parent(Args...){
//set params
}
}

Or the composition model :

class Child {
Parent p;
int param1;
int param2;
}

You can directly set the parent in that case.

You can also use Apache Commons BeanUtils to do this. Using its BeanUtils class you have access to a lot of utility methods for populating JavaBeans properties via reflection.

To copy all the common/inherited properties from a parent object to a child class object you can use its static copyProperties() method as:

BeanUtils.copyProperties(parentObj,childObject);

Note however that this is a heavy operation.

Python, how to convert an existing parent class object to child class object

Basically all attributes from a class live inside the magic __dict__ attribute. This dictionary-like object contains all the attributes defined for the object itself.

So a way to copy all attributes at once will be to copy the __dict__ attribute from a class to another either inside a method or from an instance like this:

a = Person()
b = Driver()
b.__dict__.update(a.__dict__)

Please note that if there are repeated attributes those will be overwritten so be careful

How to downcast parent class to inherited child class in hibernate?

There are two ways of typecasting :

  • Upcasting (child class to parent class & child class to child class)

  • Downcasting (parent class to child class)

Example of the issue faced by you.

package com.example;

class UserDO {

//..
}

class ReviewerDO extends UserDO {

private String reviewerType;

public ReviewerDO(String reviewerType) {
this.reviewerType = reviewerType;
}

}

public class Example {

public static void main(String[] args) {

UserDO user = new UserDO(); // upcast (child to child)
/*
* This will throw ClassCastException as direct downcasting
* is not possible.
*/
ReviewerDO reviewerDO = (ReviewerDO) user; //downcast

}

}

Output :

Exception in thread "main" java.lang.ClassCastException: com.example.UserDO cannot be cast to com.example.ReviewerDO

The solution can be in two ways :

  1. Indirect Downcasting.

For example :

package com.example;

class UserDO {

//..
}

class ReviewerDO extends UserDO {

private String reviewerType;

public ReviewerDO(String reviewerType) {
this.reviewerType = reviewerType;
}

}

public class Example {

public static void main(String[] args) {

UserDO user = new ReviewerDO(); // upcast (child to parent)
/*
* Here downcasting happens. This doesn't throw
* ClassCastException.
*/
ReviewerDO reviewerDO = (ReviewerDO) user; //downcast happens indirectly.

}

}

  1. Recommended: Create your own helper class and create custom method to copy values of one object into another using getters and setters.

For example :

public void assignUserToReviewer(UserDO userDO) {
ReviewerDO reviewerDO = Helper.createReviewerDO(userDO);
reviewerDO.setReviewerType("COMPLIANCE");
reviewerRepository.save(reviewerDO);
}

public final class Helper {

public static ReviewerDO createReviewerDO(UserDO userDO) {
ReviewerDO r = new ReviewerDO();
r.setSomething(userDO.getSomeThing());
...
return r;
}

}


Related Topics



Leave a reply



Submit