Paul Woitaschek
Paul Woitaschek

Reputation: 6807

Implementing interface depending on current API

How can I implement an interface only in some cases?

Lets say, we have int sdkVersion and only if its higher than 10 the interface TenPlusInterface exists.

For code in methods, I could just check it and say:

if (sdkVersion > 10) {
    ClassForApiTen cls = new ClassForApiTen();
    ...
}

But if my sdkVersion < 10, I cannot do a public class MyClass implements TenPlusInterface. So what would be a recommended way to implement the interface only in defined cases?

Upvotes: 0

Views: 39

Answers (2)

Vipin Singh
Vipin Singh

Reputation: 21

Create an abstract class. And based on the condition I.e.>10 or <10 you can write anonymous the inner class.

Upvotes: 0

Daniel
Daniel

Reputation: 4549

Have a subclass of your class, and have that subclass implement the interface.

public class MyClass { ... }

public class TenPlusMyClass extends MyClass implements TenPlusInterface {}

public class MyClassFactory {
     MyClass getMyClass(int sdkVersion) { 
        return sdkVersion > 10 ? new TenPlusMyClass() : new MyClass();
     }
}

Upvotes: 2

Related Questions