rdonuk
rdonuk

Reputation: 3956

Java inheritance; extends from a changeable type

Can I create a subclass which parent is dynamic? For example; on class A extends B code, can I change B according to a condition? If can I return it from a method what will be the method's return type? I mean class A extends getClassAccToCondition() return type.

Upvotes: 1

Views: 171

Answers (5)

rdonuk
rdonuk

Reputation: 3956

I decide to use a way like a variation of simple polymorphism with Factory pattern. It will work for me i think. Thanks for answers.

public class Main {
    public static I getClassBelongToCondition(boolean Condition) {
        if (Condition) {
            return new A();
        } else {
            return new C();
        }
    }

}

interface I {
}

class A extends B implements I {
}

class C extends D implements I {
}

class B {
}

class D {
}

Upvotes: 0

kutschkem
kutschkem

Reputation: 8163

You can not define a class that is not statically typed at compile time. However, you can generate classes at runtime, take a look at javassist. That being said, code generation is not the only option. If you don't need a dynamic superclass but only an interface, you can use dynamic proxies.

Upvotes: 0

Prateek
Prateek

Reputation: 551

Technically, its not possible to achieve this in java. However, I would like to try and solve actual business problem using polymorphism and some sort of factory method pattern. Not sure, if this is helpful to you but varying parent is not achievable in java.

Upvotes: 0

Michael
Michael

Reputation: 5062

As the other answers already say this is not possible.

For this kind of problem you could use the factory pattern. If you have a class hierarchy like this:

class SuperType { ... }
class SubType1 extends SuperType {...}
class SubType2 extends SuperType {...}

You could have a factory like this:

class Factory {
  public static SuperType create (Condition cond) {
    if(cond.matchForType1())
      return new SubType1();
    else
      return new SubType2();
  }
}

You can than call this method via Factory.create(<condition that match for the required type>).

If you search for "factory pattern" + "java" you will find a lot of better examples.

Upvotes: 2

Kyle
Kyle

Reputation: 893

No, the class that you are extending has to be explicitly stated.

Upvotes: 0

Related Questions