1

Suppose I have an interface:

interface MyInterface <T>;

then suppose I have multiple implementations

public class Imp1 implements MyInterface<Object>
public class Imp2 implements MyInterface<Object2>

Can I reuse same interface variable without specifying a type?

so say,

MyInterface var1 = new Imp1();
var1 = new Imp2();

oppose to having to do this:

MyInterface var1<?> = new Imp1();

Or must I always do that/live with that warning?

Here is what I need.

I am using selenium for test automation.

I have an interface that is a table. Which represents a html table for getting rows. Next I have type methods that return the equivalent pojo object. For example a cars table will return a cars object. One table could be used on many pages, and each different page could return a different pojo object.

4
  • 1
    What is the purpose of reusing this variable? To confuse code reviewer? Commented May 7, 2015 at 20:35
  • updated my question to include my actual use case. Commented May 7, 2015 at 20:39
  • Ok, I see, but if you don't know particular type in compilation time (if POJO is car or tractor or smth else), you cannot avoid the need to remember class of POJO and use it as argument in methods that process it (e.g. in switch statement where you'll cast it to particular class). Commented May 7, 2015 at 20:44
  • Are you referring to using the factory pattern? Commented May 7, 2015 at 21:06

1 Answer 1

1

For your case, you can declare the variables like this:

MyInterface<Object> var1 = new Imp1();
MyInterface<Object2> var2 = new Imp2();

And there's no need to deal wth the warning at all.

If you want/need to use it without providing the generic type, this is, using the interface with raw type, then you have to live with the warning.

Anyway, you can supress the warning by using @SupressWarnings like this.

@SupressWarnings("rawtypes")
void foo() {
    MyInterface var1 = new Imp1();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.