Sunday, 16 June 2019

Class Name of anonymous class


App.java
package com.sample.app;

public class App {

      public static void main(String args[]) {
            Object obj1 = new Object() {
                  
            };
            
            Object obj2 = new Object() {
                  
            };

            System.out.println(obj1.getClass());
            System.out.println(obj2.getClass());

      }
}

When you ran above program, you will get below output.

class com.sample.app.App$1
class com.sample.app.App$2

‘App$1’ means first anonymous class under App. ‘App$2’ means second anonymous class under App.

‘App$1’ doesn’t mean that it is a subclass of App.


App.java
package com.sample.app;

public class App {

      public static void main(String args[]) {
            Object obj1 = new Object() {

            };

            Object obj2 = new Object() {

            };

            System.out.println(obj1.getClass());
            System.out.println(obj2.getClass());

            boolean b1 = obj1 instanceof Object;
            boolean b2 = obj2 instanceof Object;

            System.out.println("obj1 instanceof Object : " + b1);
            System.out.println("obj1 instanceof Object : " + b2);

            b1 = obj1 instanceof App;
            b2 = obj2 instanceof App;

            System.out.println("obj1 instanceof App : " + b1);
            System.out.println("obj1 instanceof App : " + b2);

      }
}

Output
class com.sample.app.App$1
class com.sample.app.App$2
obj1 instanceof Object : true
obj1 instanceof Object : true
obj1 instanceof App : false
obj1 instanceof App : false



You may like



No comments:

Post a Comment