OneMoreVladimir
OneMoreVladimir

Reputation: 1673

Cannot instantiate an anonymous class

I am getting 2 errors on this simple piece of code:

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

        };
    }
}

Errors:

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

What is wrong here?

Upvotes: 3

Views: 812

Answers (3)

Andreas
Andreas

Reputation: 5335

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

With this rule, the code fails since there is NO existing class (type) O.

Try to define the class and use polymorphism to override the methods you want in the parent class.

Upvotes: 3

Cosmin Cosmin
Cosmin Cosmin

Reputation: 1556

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

Upvotes: 1

Charlie Martin
Charlie Martin

Reputation: 112366

As the comment says, you have to define the class somewhere. This code should work:

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

        };
    }
}

Upvotes: 2

Related Questions