sokras
sokras

Reputation: 629

Java class implementation error

So I am doing a project and I have 2 interfaces.

Let's call them:

public interface A{

}
public interface B{

}

And I have 4 different classes that implement these interfaces, because I need to either run them locally or over the network:

public class Class1 implements A{ 
  // logical implementation of A
}
public class Class2 implements B{ 
  // logical implementation of B
}
public class Class3 implements A{ 
  // proxy implementation of A
}
public class Class4 implements B{ 
  // proxy implementation of B
}

Class1 and Class3 implement the logic of the interfaces while Class2 and Class4 implement the Proxies of these interfaces. I am now trying to test these classes and I have the following code:

private static Class1 object1;
private static Class2 object2;

if (localTest) {
      object1 = new Class1();
      object2 = new Class2();
} else {
      object1 = new Class3();
      object2 = new Class4();
}

According to the code above I get the error that the class of object1 is incompatible with Class3 and so is the class of object2 with Class4.

Since Class1 and Class3 implement the same interface and Class2 and Class4 implement the same interface, why do i get the error?

I am sorry if i cannot get in any more specifics.

thanks

Upvotes: 1

Views: 1032

Answers (3)

Eran
Eran

Reputation: 394136

When two classes implement the same interface, you can't assign an instance of one class to a variable of the other class's type. The two classes may have different methods (other than the common methods of the interface). Therefore a Class1 variable can only hold instances of Class1 or sub-classes of Class1.

It would make more sense if you use the interface types A and B for your variables, since a variable of type A can hold any implementation of that interface.

private static A object1;
private static B object2;

if (localTest) {
      object1 = new Class1();
      object2 = new Class2();
} else {
      object1 = new Class3();
      object2 = new Class4();
}

Upvotes: 1

timrau
timrau

Reputation: 23058

Because Class3 did not inherit from Class1, and Class4 did not inherit from Class2.

What you expect may be

private static A object1;
private static B object2;

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

The references need to be the correct interface types. Something like,

private static A object1; // <-- not Class1
private static B object2; // <-- not Class2

An A can refer to a Class1 or a Class3 and a B can refer to a Class2 or a Class4. But a Class1 cannot refer to a Class3 (nor can a Class2 refer to a Class4).

Upvotes: 1

Related Questions