java - Why do these two apparently identical objects have different class types? -


this question has answer here:

i have class user, have 2 fields: id, name

package test;  public class user {     private long id;     private string name;      public long getid() {         return id;     }      public void setid(long id) {         this.id = id;     }      public string getname() {         return name;     }      public void setname(string name) {         this.name = name;     } } 

then in main class, tried initialize user object 2 different approach:

package test;  /**  * @author lhuang  */ public class main {     public static void main(string[] args) {         user u = new user() {             {                 setid(1l);                 setname("lhuang");             }         };          system.out.println(u.getclass());          user u2 = new user();         u2.setid(1l);         u2.setname("lhuang");         system.out.println(u2.getclass());     } } 

then can output

class test.main$1 class test.user 

the interesting why u class inner class type of main? still can use u.getid() , u.getname() method.

you're creating anonymous class extends user here:

user u = new user() { //<-- open bracket defines new class         {             setid(1l);             setname("lhuang");         }     }; 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -