1 /*
 2  * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
 3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 4  *
 5  * This code is free software; you can redistribute it and/or modify it
 6  * under the terms of the GNU General Public License version 2 only, as
 7  * published by the Free Software Foundation.
 8  *
 9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 /*
25  * @test
26  * @run main Nest
27  * @summary Test substitutability of inner class and anonymous class that
28  * has the enclosing instance and possibly other captured outer locals
29  */
30 
31 public interface Nest {
32     public static void main(String... args) {
33         assertEquals(Nest.of(1, null), Nest.of(1, null));
34         assertNotEquals(Nest.of(1, null), Nest.of(2, null));
35 
36         Outer n = new Outer(1);
37         Outer.Inner inner = n.new Inner(10);
38         Outer n1 = new Outer(1);
39         Outer n2 = new Outer(2);
40         assertEquals(n1.new Inner(10), inner);
41         assertEquals(n2.new Inner(10), new Outer(2).new Inner(10));
42     }
43 
44     // o1.new Inner(1) == o2.new Inner(1) iff o1 == o2
45     static primitive class Outer {
46         final int i;
47         Outer(int i) {
48             this.i = i;
49         }
50 
51         primitive class Inner {
52             final int ic;
53             Inner(int ic) {
54                 this.ic = ic;
55             }
56         }
57     }
58 
59     String toString();
60 
61     static Nest of(int value, Object next) {
62         // anonymous class capturing outer locals
63         return new primitive Nest() {
64             public String toString() {
65                 return value + " -> " + next;
66             }
67         };
68     }
69 
70     static void assertEquals(Object o1, Object o2) {
71         if (o1 != o2) {
72             throw new RuntimeException(o1 + " != " + o2);
73         }
74     }
75     static void assertNotEquals(Object o1, Object o2) {
76         if (o1 == o2) {
77             throw new RuntimeException(o1 + " == " + o2);
78         }
79     }
80 }