Pergunta

I'm describe a class

public class MyClass{ ... }
public class Main{
    public static void main(String[] args){
        MyClass m= new MyClass(){ };
        System.out.println(m.getClass.getName);
    }
}

output:

main.Main$1

And what this output does mean? I describe anonymous class, hence m has anonymous type. I expected a NullPointerException be thrown.

Foi útil?

Solução

I'm excepted NullPointerException.

Why? Which part of the code made you expect this?

And what this output does mean?

The anonymous class used in your class are numbered in the order in which they appear in the class. main.Main$1 means that was the first anonymous class created.

For example, consider this example:

class MyClass { }

public class Demo {

    static MyClass obj = new MyClass() { 
        { 
            System.out.println("static field: " + this.getClass().getName());
        }
    };

    MyClass obj2 = new MyClass() { 
        { 
            System.out.println("instance field: " + this.getClass().getName());
        }
    };    

    public static void main(String[] args) {
        Demo obj4 = new Demo();

        MyClass obj3 = new MyClass() { 
            { 
                System.out.println("local variable: " + this.getClass().getName());
            }
        };    

    }
}

Don't worry about those blocks. Those are just instance initializer blocks in each anonymous class.

When you execute this code, you will get the following output:

static field: Demo$1
instance field: Demo$2
local variable: Demo$3

Now try moving the static field after the instance field, and see what name they get.

Outras dicas

And what this output does mean?

Main$1 means first anonymous class under Main.

Note:- $ denotes for inner class

I'm excepted `NullPointerException.

Why you are expecting so? Please provide few reasons for that. :)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top