开发者

abstract class and anonymous class [duplicate]

开发者 https://www.devze.com 2023-02-13 22:50 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: abstract class and anonymous class
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

abstract class and anonymous class

abstract class Two {
    Two() {
        System.out.println("Two()");
    }
    Two(String s) {
        System.out.println("Two(String");
    }
    abstract int  display();
}
class One {
    public Two two(开发者_StackOverflow中文版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 method Two two(String s) in class One returns an object of abstract class Two


As your question title suggests, you're instantiating an anonymous inner class that extends from Two, not Two itself.


As your title suggests, the method two() creates an instance of an anonymous class extending Two (and implementing the abstract method display().

This One implementation has pretty much the same result (except that the class is named now).

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

    private static class MyTwo extends Two {
       public int display() {
            System.out.println("display()");
            return 1;
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号