Hello, I’m having a hard time to understand why it works, I know it works and how it works, but I don’t really grasp the ‘behind the scenes.’
Let’s have a code for the subject’s sake:
`interface X {void wassup();}`
`class Y implements X {public Y() {System.out.println(“y”);}`
`public void wassup() {System.out.println(“wassup”);}}`
`class HelloWorld {`
`public static void main(String[] args) {`
`returnInterface();}`
`public static X returnInterface() {System.out.println(“Hello World”);return new Y();}}`
How and why can we return a class even though it expects an interface?
`X test = new Y();`
`Y test = new Y();`
What’s the difference? One is type of interface, one is type of class, is that all?
For the `X test = new Y();` , is ‘test’ variable a type of interface? Just like string, int or float?
So ‘test’ variable has all the features of X class has, like its variables, methods?
And does ‘test’ variable execute its features/codes/methods in the context of Y?
Does ‘new’ keyword goes and allocate memory in the ram, amount of the variable and methods contains in Y class or X interface?
In: Engineering
**How and why can we return a class even though it expects an interface?**
The compiler will cast the object of type Y to the interface X. This works because you have said that class Y implements interface X. The compiler is smart enough to cast the type even if you did not ask for it.
**X test = new Y();**
**Y test = new Y();**
**What’s the difference? One is type of interface, one is type of class, is that all?**
In your first example the variable test is of type X while in the second one it is of type Y. If you had implemented additional public meathods in the class Y this would be available to anyone using the variable in the second case but not the first. That is basically the only difference.
**For the** **X test = new Y();** **, is ‘test’ variable a type of interface? Just like string, int or float?**
Yes, the variable is of type X, which is the interface.
**So ‘test’ variable has all the features of X class has, like its variables, methods?**
Exactly. All public meathods and variables in the interface is available. However when the variable is of type X you do not have access to the public methods and varables in the class Y.
**And does ‘test’ variable execute its features/codes/methods in the context of Y?**
Yes. When you call a public meathod it will get passed to the object that the varible points to and this is of type Y. So even though the variable is of type X the object within it is of type Y which is what determines what code will run.
**Does ‘new’ keyword goes and allocate memory in the ram, amount of the variable and methods contains in Y class or X interface?**
The content of the memory will be an object of class Y. There is not actually any objects of type X because this is an interface. Only variables can have type X and not the actual objects that the variables point to.
Latest Answers