So, I want to create a correlation between two classes, from what I have read in some design patterns, it convenient, to use an interface, (in Android Studio it is used to bind a fragment with a activity).
Look at this code:
First, we have class A:
public class A {
public static void main(String[] args) {
B b = new B();
b.foo();
}
}
Then, we have class B:
class B {
private int i;
interface Drawable {
void show(int i);
}
public B() {
this.i = 5393;
drawable = new C();
}
private Drawable drawable;
public void foo() {
drawable.show(this.i);
}
}
And at the end class C:
class C implements B.Drawable {
@Override
public void show(int i) {
System.out.println("I'm showing this method, and i = " + i);
}
}
What I'm wrapping my head around is this line:
drawable = new C();
Can someone explain me how are we assigning new object from class C, to a interface, I know it is because class C implements that interface, yet, it is hard for me to get it all. The general view of this operation is pretty harsh for me to overcome.
In Android we are assigning that interface to a Activity, (the recent patch changed it into a context, which is a instance of a Activity).