to problem set

Problem 4 - Inheritance problem

public interface InterA extends InterB {...}
public interface InterB {...}
public interface InterC extends InterA, InterD {...}
public interface InterD {...}
public class A implements InterA {...}
public class B implements InterB {...}
public class C extends B implements InterC {...}
public class D extends B implements InterD {...}
public class E extends D implements InterA {...}
A a1 = new A();
B b1 = new B();
C c1 = new C();
D d1 = new D();
E e1 = new E();

Now our job is to decide whether each one of these is legal or not.

InterA ia1 = (InterA) c1; // Legal
InterB ib1 = (InterB) d1; // Legal
A a2 = (A) e1; // Illegal
InterC ic1 = (InterC) a1; // Illegal
B b2 = (B) e1; // Legal
InterC ic2 = (InterC) d1; // Illegal
InterA ia2 = (InterA) c1; // Legal
D d2 = (D) c1; // Illegal
InterB ib2 = (InterA) ((B) c1); // Legal
InterD id1 = (D)((B) e1); // Legal

Lets start by first diagramming our interfaces and what they extend

interA is a interB
interB is a 
interC is a interA, interD
interD is a

now lets do our classes.

classA is a interA
classB is a interB
classC is a classB, interC
classD is a classB, interD
classE is a classD, interA

The key is to start with the outermost item. Then you look to see what it is trying to cast to.

  1. if it is being cast to an interface… you follow the is a tree including every class and all interfaces.
  2. if it is being cast to a class… you follow the is a tree ONLY including the classes.

Work your way backwards up the chain following each path until it runs out. For example look below. We are going to start with the class of type c1, classC, and work to find a connection to interA.

1.) InterA ia1 = (InterA) c1;
so I don’t care about the left side of the equation. Lets look at the right side and see what we have. First we are taking a classC and trying to cast it to an interA. Is this possible? We start with looking at classC.

So it is legal.

2.) InterB ib1 = (InterB) d1;

legal
3.) A a2 = (A) e1;
This one is a little different. Before we were able to look at classes and the interfaces they implemented. Now we are JUST going to look at the classes.

illegal
4.) InterC ic1 = (InterC) a1;

no interface c found

illegal
5.) B b2 = (B) e1;
Here we have classes again, so we cant include the interfaces and we only care about extending other classes.

legal
6.) InterC ic2 = (InterC) d1;
So I’m looking to see if d1 reaches interfaceC by any means.

illegal
7.) InterA ia2 = (InterA) c1;

legal

8.) D d2 = (D) c1;
looking ONLY at classes again

illegal

9.) InterB ib2 = (InterA) ((B) c1);
PEMDAS, we are going to start with the first part and move outwards.

legal

10.) InterD id1 = (D)((B) e1);

so we passed the first test, now for the second part

legal