Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I specify as return type of a method the type of the object upon which the method is called?

Let's say I have an Interface 'Inter', and Inter has a method

Inter someMethod();

How can I specify that the type of the return object has to be the same as the object upon which the method is called? So if I have two classes 'C1' and 'C2' that implement Inter, if an instance of C1 calls someMethod (c1.someMethod()) the result will be an instance of C1, whereas if an instance of C2 calls someMethod the result will be an instance of C2.

How about parameters? If Inter has a second method

void someMethod2(Inter inter)

How can I specify that the parameter has to be an instance of the same class as the object calling the method?

like image 542
user2460978 Avatar asked Jun 29 '13 20:06

user2460978


Video Answer


2 Answers

Using Generics.

public interface Inter<T> {

    T someMethod();
    void someMethod2(T obj);

}

public class C1 implements Inter<C1> {

    public C1 someMethod() {
      // ..
    }

    public void someMethod2(C1 obj) {
      // ..
    }

}

public class C2 implements Inter<C2> {

    public C2 someMethod() {
      // ..
    }

    public void someMethod2(C2 obj) {
      // ..
    }

}

Reference :
Generic Types (The Java™ Tutorials > Generics)

Edit : (Using a bounded generic type; in response to OP's comments)

public interface Inter<T extends Inter<T>> {

    T someMethod();
    void someMethod2(T obj);
}

public class C1 implements Inter<C1> {

    public C1 someMethod() {
        return new C1();
    }

    public void someMethod2(C1 obj) {
      // ..
    }
}

public class C2 implements Inter<C3> { // ERROR
    ..
}

But, here comes the catch.

public class C2 implements Inter<C1> { // COMPILES!
    ..
}

Because, C1 also satisfies T extends Inter<T>. This is as far as this can go I believe.

Reference :
Bounded Type Parameters (The Java™ Tutorials > Generics)

like image 99
Ravi K Thapliyal Avatar answered Nov 14 '22 22:11

Ravi K Thapliyal


You can try something like this

public interface Inter<T> {

    public T doSomething();
}

public class C1 implements Inter<C1> {

    @Override
    public C1 doSomething() {
        return new C1();
    }
}

public class C2 implements Inter<C2> {

    @Override
    public C2 doSomething() {
        return new C2();
    }
}
like image 45
Suresh Atta Avatar answered Nov 14 '22 23:11

Suresh Atta