3
abstract class Two {
    Two() {
        System.out.println("Two()");
    }
    Two(String s) {
        System.out.println("Two(String");
    }
    abstract int  display();
}
class One {
    public Two two(String s) {
        return new Two() {          
            public int display() {
                System.out.println("display()");
                return 1;
            }
        };
    }
}
class Ajay {
    public static void main(String ...strings ){
        One one=new One();
        Two two=one.two("ajay");
        System.out.println(two.display());
    }
}

we cannot instantiate an abstract class then why is the function Two two(String s) able to create an instance of abstract class Two ????

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
tin_tin
  • 478
  • 3
  • 10
  • 24

2 Answers2

11

It does not create an instance of abstract Two. It creates a concrete, anonymous class that extends Two and instantiates it.

It's almost equivalent to using a named inner class like this:

class One {
    public Two two(String s) {
        return new MyTwo();
    }

    class MyTwo extends Two {
        public int display() {
            System.out.println("display()");
            return 1;
        }
    }
}
Konrad Garus
  • 53,145
  • 43
  • 157
  • 230
2

Because it implements the missing function display(). It returns an anonymous subclass of Two. You can see this if you look at the compiled files. You will have a One$1.class there, which extends Two.class!

Daniel
  • 27,718
  • 20
  • 89
  • 133