Results 1 to 4 of 4
Thread: Constructor vs Abstract
- 01-14-2012, 09:14 AM #1
Member
- Join Date
- Jan 2012
- Posts
- 55
- Rep Power
- 0
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.
- 01-14-2012, 10:29 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,537
- Rep Power
- 11
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 10:35 AM.
- 01-14-2012, 11:12 AM #3
Member
- Join Date
- Jan 2012
- Posts
- 55
- Rep Power
- 0
Re: Constructor vs Abstract
Thanks a ton!!! tht was hugely helpful.
- 01-14-2012, 11:29 AM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,537
- Rep Power
- 11
Similar Threads
-
Class is not abstract and does not override abstract method run(com.
By rgeurts in forum New To JavaReplies: 4Last Post: 04-14-2011, 11:42 AM -
Not abstract and doesn't override abstract method keyReleased
By cc11rocks in forum AWT / SwingReplies: 4Last Post: 02-19-2011, 04:32 AM -
SkeletonMidlet is not abstract and does not override abstract method
By just_in_deed in forum CLDC and MIDPReplies: 3Last Post: 08-13-2010, 04:57 AM -
...is not abstract and does not override abstract method...
By Addez in forum New To JavaReplies: 3Last Post: 09-16-2009, 09:27 PM -
GameImpl is not abstract and does not override abstract method
By Macca07 in forum New To JavaReplies: 2Last Post: 11-21-2008, 12:20 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks