Unable to instantiate anonymous class

I get 2 errors in this simple code:

public class Test {
    public static void main(String args[]) {
        O o = new O() {

        };
    }
}

Errors:

    Test.java data: cannot find symbol
    symbol: class O
    location: class Test                                  
    O o = new O () {                               
    ^
    Test.java data: cannot find symbol                       
    symbol: class O                                     
    location: class Test                                  
    O o = new O () {                               
                      ^                                   

What is wrong here?

+3
source share
3 answers

With anonymous inner classes, you must extend an existing class (and use Polymorphism to override methods) or an existing interface.

With this rule, the code crashes because there is no existing class (type) O.

, .

+3

, -. :

class O {}
public class Test {
    public static void main(String args[]) {
        O o = new O() {

        };
    }
}
+2

Try:

public class Test {
    public static void main(String args[]) {
        Test  o = new Test () {

        };
        System.out.println(o.getClass().getName());
    }
}

you will get Test $ 1

+1
source

All Articles