Kiss Péter
Kiss Péter

Reputation: 31

Passing on an Interface as a constructor to a class

Here's My code:

public interface Baseinterface {}
abstract class Interface1 implements Baseinterface{}
abstract class Interface2 implements Baseinterface{}

public interface Classinterface {}

And i want to use this code:

public class Myclass(Baseinterface interfaceversion) implements  Classinterface{}

Where the kind of interface implementation is passed as a constructor. So when a function is defined in both of those abstract classes my actual class knows which one to use. I am fairly new at java. Thanks.

Upvotes: 0

Views: 322

Answers (1)

Julian
Julian

Reputation: 1675

I may be misunderstanding the nature of the question, but here goes:

Given this code which describes two abstract classes that implement the same method as defined by an interface:

interface BaseInterface {
    void foo();
}

abstract class ITestA implements BaseInterface {
    public void foo() {
        System.out.print("A");
    }
}

abstract class ITestB implements BaseInterface {
    public void foo() {
        System.out.print("B");
    }
}

public class MyClass {
    private BaseInterface enclosed;

    MyClass(BaseInterface base) {
        enclosed = base;
    }

    public void foo() {
        enclosed.foo(); // call the implementation specific to the instance passed in by constructor
    }
}

This could be called like:

    public class Test {
    void bar() {
        // This may look weird cause we're defining an anonymous implementation of the abstract class, without adding any new implementation details
        ITestA impl = new ITestA() {}; 

        MyClass myClass = new MyClass(impl);
        myClass.foo(); // prints "A"
    }
}

Upvotes: 1

Related Questions