0

I have a variable: Abstract a. It is a class that extends the Abstract class. However, I need to cast this Abstract variable into a more specific class variable that extends the Abstract class.

My situation: I have two classes, Class1 and Class2 that both extend the Abstract class with methods implemented in each one. I now have an Abstract class variable to work with. I do not know if it is Class1 or Class2, so I cannot simply do a (Class1) a or a (Class2) a (casting).

So how would I successfully cast this variable so that I can use the inner methods?

I was thinking along the lines of using a.getClass().getName() to determine how to cast it, but I am stuck from here on out.

Dylan Wheeler
  • 6,928
  • 14
  • 56
  • 80
  • Can you post the sample code where your variable is defined and used? It's not clear that the variable you are talking about is a method argument, a local variable or an instance variable. – Genzer Jul 14 '12 at 18:27
  • Updated my answer per your new question. Agree with @Genzer, a code sample would be very helpful here. – dimo414 Jul 16 '12 at 15:04

3 Answers3

1

Your new question appears to be asking how to dynamically cast a variable to an arbitrary type unknown at runtime. This is probably a duplicate of java: how can i do dynamic casting of a variable from one type to another? but to summarize, this is not (easily) possible, isn't recommended, and speaks to other issues in your code.

Think about it this way, what variable would you possibly be able to use to store your newly cast object? Imagine if we had a (child) cast operation in Java, that took a variable defined as a parent class, and cast it down to its child (e.g. List -> LinkedList):

public static void func(Abstract a){
    ???? var = (child)a;
    // Do something with var?
}

Notice that 1) there's no way you could ever specify a type for var, since we don't know at runtime what type it will be; and 2) there's nothing we'd be able to do with var beyond the behavior defined in Abstract anyways, because the compiler can't predict which methods will be availible to var other than what's available to Abstract.

If you need to implement class-specific behavior, you should do so inside the class. Have an abstract method which each class has to implement, and which can do whatever you need them to do. Or, if you cannot ensure that, don't define a function that takes an Abstract as an argument; instead define however many functions that take Class1, Class2, etc. objects as parameters, like so:

Abstract method to require all child classes behave similarly

public abstract class Abstract{
  /** Do the class-specific behavior you want to do currently in func */
  public abstract void operation();

  public static void func(Abstract a){
    a.operation();
  }
}

Functions only for classes that can actually handle what you want

public static void func(Class1 a){
  // do something
}

public static void func(Class2 a){
  // do something
}

Again, if neither of these options are viable for you (and of course, blocks of instanceof calls aren't acceptable) then I'd be willing to bet money there's something structural in the way you're using Java that's fundamentally incorrect. If you want to post a code sample of exactly what you're trying to accomplish by child-casting, perhaps we can shed some light as to what the issue is.


Leaving this here for posterity - OP's original question asked about creating new instances of an object cast as its abstract parent.

Pretty straightforward, get the object's class object, and create a new instance. For more complex constructors, see the Java documentation on creating new instances dynamically.

public class ClassVar
{
    public static abstract class Abstract
    {

    }

    public static class Class1 extends Abstract
    {

    }

    public static class Class2 extends Abstract
    {

    }

    /**
     * Given an instance of a child of Abstract, returns a new instance
     * of the same class
     */
    public static Abstract newInstance(Abstract obj) throws InstantiationException, IllegalAccessException
    {
        return obj.getClass().newInstance();
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException
    {
        System.out.println(newInstance(new Class1()).getClass());
        System.out.println(newInstance(new Class2()).getClass());
    }
}

Result:

class ClassVar$Class1
class ClassVar$Class2
Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244
0

Basically you can use reflection by using

Class cl = ...

cl.newInstance()

The more 'expanded' answer you can find here

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

Since you edited your question again 3h ago at the time of writing here's my second answer to a problem I thought was solved. It's obvious nobody got what you're really asking for in the first place. Try to improve how you're asking questions.
However, the answer is simple:

  • From the point of view of object orientation you simply shouldn't have to (Liskov Substitution principle). Even if you have exact knowledge about exactly two possible instances, you should look for a better approach for the problem you are trying to model.

  • If you have to, determine the class name and check for equality or carry an extra identifier and compare that one. Implementation couldn't be simpler.

f4lco
  • 3,728
  • 5
  • 28
  • 53
  • I understand what you are trying to say, but how can I do this? Let's just say I have 100 classes that extend Abstract. I don't want to use "if" statements at such a length. – Dylan Wheeler Jul 15 '12 at 20:33