Interfaces, classes, new keyword, behind the scenes

592 views

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

3 Answers

Anonymous 0 Comments

Interface is like…. a specification. There’s no content inside it.

Class Y is an implementation of that interface, which means it has to follow the specification.
You could for example have a class Z, which is also implementation of interface X. It would also have method wassup(), but you could make it return something else.

>How and why can we return a class even though it expects an interface?

The class is an implementation of that interface, so it’s valid. Actually, returning interface always returns an implementation of it (a class)

>What’s the difference? One is type of interface, one is type of class, is that all?

Yes, if you were to debug the code, you’d see both of the objects are class Y.

X test = new Y();

this creates a new object of class Y

I could go on but I will finish here: You will maybe look at this all and think –

>wait a minute – interfaces are useless, I can just use classes without ever using interfaces.

And yes, you technically can. But interfaces are far from useless. So just get used to them.

You are viewing 1 out of 3 answers, click here to view all answers.