2
String child = "C";
Parent p = null;
try {
    Class c1 = new Class.forName(child);
    Constructor co = c1.getConstructor();
    // p=co.newInstance(null); //This gives compilatoin error cannot
    // conver object to Parent
    // p=(c1.getClass())co.newInstance(null);//also gives cast errror
    p = (Parent) co.newInstance(null);// this works but it typecasts the
    // child to Parent
} catch (Exception e) {
}

What am i trying to do.

I have multiple Child classes inherited from Parent. I am getting child class name as string input.

I want to instantiate the object of Child class and assign it to Parent. I do not want to type cast Child to Parent. As later in the code i need to compare two Child classes. If I typecast it to Parent. I cannot differentiate between Child1 and Child2.

2
  • How do you compare your child1 and child2? Commented Jul 8, 2011 at 4:23
  • 1
    You might want to check out Polymorphism. Commented Jul 8, 2011 at 4:25

3 Answers 3

4

Typecasting has absolutely no effect on the object itself. Using p = (Parent) t simply does a runtime check on t to make sure that the type of t is assignable to Parent (i.e. either t is-a Parent or it is-a subclass of Parent) . Afterward, t will still be a Child1 or whatever its actual type always has been.

Use the explicit cast.

Sign up to request clarification or add additional context in comments.

2 Comments

What if we want to use methods of child class in this scenario? How to get reference variable of child class?
@zookastos: If an instance of the child class is what you need, that's what you should cast to. If you only care that it's some child of a certain parent, cast it to the parent.
1

You might try something like:

Object parent = null;
String child = String.class.getName();  //not necessary, can just use String.class directly
Class childClass = Class.forName(child);
Class parentClass = Object.class;

if (parentClass.isAssignableFrom(childClass)) {
    parent = childClass.newInstance();
}

System.out.println("Parent is:  " + parent);

Comments

0

Even the Parent is cast form the 2 different children as

Parent parent1 = (Parent)child1;
Parent parent2 = (Parent)child2;

The parent1 and parent2 are totally different based on each child.

You may see the difference by printing them as

System.out.println(parent1.getClass().getName());
System.out.println(parent2.getClass().getName());

Then you may compare it by using the getName() as well.

I hope this may help to achieve the requirement.

Regards,

Charlee Ch.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.