Results 1 to 7 of 7
Thread: create an object of interface
- 04-16-2011, 03:51 AM #1
Member
- Join Date
- Apr 2011
- Posts
- 52
- Rep Power
- 0
create an object of interface
It is said we cannot create an object of interface. What about the next code
List myIntList = new LinkedList();
Is List an interface?
The code is on page 2 of http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
Thanks.
- 04-16-2011, 03:55 AM #2
List is an interface, but you are not instantiating an object of List, you are instantiating an object of LinkedList.
- 04-16-2011, 03:56 AM #3
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
It is an interface. List is not the actual object. It is the type. The reference type can be of any superclass or interface the class implements. You could also do
You can also create an array of some interface type and fill it with implementing classes.Java Code:Object o = new String("Hi");
It has something to do with polymorphism, but it gets a bit more complicated then that. I would try and google and see what you can find out about this topic.
- 04-16-2011, 03:56 AM #4
Yes List is an interface but the code does not create an instance of List, it creates an instance of LinkedList which is a concrete class.
[mutter]
stoopid phone call
[/mutter]
- 04-16-2011, 04:12 AM #5
Member
- Join Date
- Apr 2011
- Posts
- 52
- Rep Power
- 0
Thank you all. Why does it not use
LinkedList myIntList = new LinkedList();
Is LinkedList myIntList = new LinkedList();
more clear?
Thanks again.
- 04-16-2011, 04:23 AM #6
It is generally accepted that you always use the interface type when declaring variables. Consider a method:
That restricts users to only be able to pass a LinkedList to the method.Java Code:public void doStuff(LinkedList l) { }
This allows any List to be passed.Java Code:public void doStuff(List l) { }
- 04-16-2011, 04:28 AM #7
Member
- Join Date
- Apr 2011
- Posts
- 52
- Rep Power
- 0
Similar Threads
-
Create extra GUI interface
By africanhacker in forum New To JavaReplies: 7Last Post: 03-27-2011, 10:05 AM -
What is best object to create?
By lam5442 in forum New To JavaReplies: 1Last Post: 02-23-2011, 09:44 PM -
Create object of unknown class, based on existing object
By Zack in forum New To JavaReplies: 2Last Post: 06-22-2010, 04:29 AM -
create object
By paul21 in forum New To JavaReplies: 4Last Post: 03-07-2010, 07:14 PM -
Create interface from my code
By Lyricid in forum AWT / SwingReplies: 1Last Post: 11-18-2009, 05:39 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks