helloMundo
helloMundo

Reputation: 87

What to return if a method returns an interface?

I am given a set of interfaces and have to create a class that implements these interfaces, however, I am confused about the return type for the interfaces that have references to other interfaces.

// Implement class C below so that the code compiles. None of the methods may return null. // You may define supplementary classes (inner-classes or "regular" classes) if you wish. // Note that C is a subclass of Object, and it implements only X and Y -- you cannot change this.

abstract class A {
abstract void q ();
}

interface Y {
int p (int j);
A me ();
}

interface X {
void m (Object o);
X n ();
}

class C implements X, Y {
// Write your code here -- make all methods public (otherwise,
// the compiler will not consider the interfaces to be "implemented")!

    @Override
public int p(int j) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public A me() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void m(Object o) {
    // TODO Auto-generated method stub

}

@Override
public X n() {
    // TODO Auto-generated method stub
    return null;
}
}

What am I suppose to return for the methods that have an interface for a return type? I am confused because you can't instantiate interfaces so what am I suppose to return?

Upvotes: 0

Views: 473

Answers (2)

Vince
Vince

Reputation: 15146

You can give a reference to an interface if you create an anonymous class. Runnable run = new Runnable() { }. The methods from your interface will be stored in your variable. This isnt instiansiating an interface, rather giving the methods contained in your interface some kind of reference.

public Runnable run() {
    return new Runnable() {
        public void run() { }
    };
}

This also applies for abstract classes. Usually, you cant directly create an instance of an abstract class new A();, but anonymous classes allow you to create a subclass of a sort, that allows you to override the methods that require a body. Creating an anonymous class is similar to creating a subclass in some ways. You have access to protected variables, and can also declare new methods.

If your interface only contains 1 method, you cpuld also use lambda expressions

Runnable run = () -> {

}

Upvotes: 1

merlin2011
merlin2011

Reputation: 75545

You will need to write a class which implements the interface and return an object of that class.

As your question says: You may define supplementary classes, so just write the classes that implement those interfaces. In the case of abstract classes, you must extend those.

class Foo extends A {
// Override abstract method
}

Since class C already implements X and Y, you can just return an object of class C (new C()), where either X or Y is required.

Upvotes: 1

Related Questions