Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot instantiate an anonymous class

Tags:

java

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?

like image 321
OneMoreVladimir Avatar asked Dec 10 '25 20:12

OneMoreVladimir


2 Answers

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.

like image 168
Andreas Avatar answered Dec 12 '25 09:12

Andreas


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() {

        };
    }
}
like image 36
Charlie Martin Avatar answered Dec 12 '25 09:12

Charlie Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!