I came across this question:
What is the output of the following?
1 public class A {
2 public static void main(String[] args){
3 I i = new I() {};
4 System.out.println(I.x + i.getValue() + "" + i);
5 }
6 }
7
8 interface I {
9 int x = 10;
10
11 public default int getValue() {
12 return 5;
13 }
14
15 public default String toString() {
16 return "I";
17 }
18 }
My thinking:
My first instinct tells me - I i = new I() {}? We can't instantiate interfaces hence - issue 1.
Then I think public default String toString()? Overriding Object class method? Doesn't sound good - issue 2
Possible answers:
a) 10I
b) 15I
c) Compilation fail due to line 11
d) Compilation fail due to line 15
e) Compilation fail due to multiple errors
Having explained my thoughts I picked answer E) which is wrong. The correct answer is D) which I also got right.
My question - why is the following statement valid?
I i = new I() {};
Is this statement doing something I don't understand due to the "{}" added to it? To my understanding the new
keyword means: instantiate.