0

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(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

Community
  • 1
  • 1
tin_tin
  • 478
  • 3
  • 10
  • 24
  • 1
    if you don't understand the answers to the last time you asked the question, don't add the question again, add comments to the existing question. – Peter Lawrey Mar 01 '11 at 12:53
  • Opps really very sorry for posting again.There was a bit of confusion at my end. I'll try to be careful in future – tin_tin Mar 02 '11 at 05:01

2 Answers2

1

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

Isaac Truett
  • 8,734
  • 1
  • 29
  • 48
0

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;
        }
    }
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614