Results 1 to 4 of 4
  1. #1
    java4amanda is offline Member
    Join Date
    Jan 2012
    Posts
    55
    Rep Power
    0

    Default Constructor vs Abstract

    I was going through constructor basics and i got a doubt when i encountered a statement saying that " an Abstract class can have a constructor and Interface cannot." An interface is a pure abstract upon which one cannot use the "new" keyword and same is with that of abstract class as well. My question is why cant we do it with interfaces? What are the pros and cons associated with the declaration of constructor inside the interface? And why that special treatment with Abstract classss?


    Thank you,

    Regards.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default Re: Constructor vs Abstract

    What makes an interface special as a type is that it has no implementation. Classes (whether abstract or not) do have implementation.

    The implementation of a class lies in its instance variables and methods. All classes have constructors - it may be that a class has only the default constructor, but it always has a constructor. The job of a constructor is to make sure that the state of an instance is properly set up with all of its instance variables properly initialised.

    Note that all three sentences in the previous paragraph apply to abstract classes just as they do to non abstract classes. And that the lack of constructors for interfaces is a reflection of the fact that interfaces do not have state or any implementation.

    -----

    You can use the "new" keyword with interfaces and abstract classes provided you follow the class with a block that provides the implementation:

    Java Code:
    MouseListener mouseListener = new MouseListener() {
        @Override
        public void mouseMoved(MouseEvent me) {}
    
        // etc for the other methods that a MouseListener
        // must have
    };
    Last edited by pbrockway2; 01-14-2012 at 11:35 AM.

  3. #3
    java4amanda is offline Member
    Join Date
    Jan 2012
    Posts
    55
    Rep Power
    0

    Default Re: Constructor vs Abstract

    Thanks a ton!!! tht was hugely helpful.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

Similar Threads

  1. Replies: 4
    Last Post: 04-14-2011, 12:42 PM
  2. Replies: 4
    Last Post: 02-19-2011, 05:32 AM
  3. Replies: 3
    Last Post: 08-13-2010, 05:57 AM
  4. Replies: 3
    Last Post: 09-16-2009, 10:27 PM
  5. Replies: 2
    Last Post: 11-21-2008, 01:20 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •