Results 1 to 4 of 4
- 07-25-2013, 12:53 PM #1
Member
- Join Date
- Feb 2012
- Posts
- 62
- Rep Power
- 0
Creating objects for class and referenced to interface
Hi ,
I want to know the advantages of creating objects for class and referencing to interface.
For example
interface test{
public void display();
}
class Testing implements test{
public void display(){
System.out.println("Inside Testing ");
}
}
class MainClass{
public static void main(String a[]){
Test testingObject = new Testing();
testingObject.display();
}
}
Here why is it a good practice to hold the testingObject in test interface?
- 07-25-2013, 01:21 PM #2
Re: Creating objects for class and referenced to interface
If you're forever cleaning cobwebs, it's time to get rid of the spiders.
- 07-25-2013, 01:37 PM #3
Just a guy
- Join Date
- Jun 2013
- Location
- Netherlands
- Posts
- 5,114
- Rep Power
- 13
Re: Creating objects for class and referenced to interface
Consider this: there is an ArrayList and a LinkedList. Now what if you wanted to make a method which does not care what kind of list it is, but just wants "any" list?
The answer:
Java Code:public void doSomethingWithAList(List<SomeObject> theList){ }
Java Code:public void doSomethingWithAList(ArrayList<SomeObject> theList){ }
"Syntactic sugar causes cancer of the semicolon." -- Alan Perlis
- 07-25-2013, 01:43 PM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 13,541
- Rep Power
- 27
Re: Creating objects for class and referenced to interface
I have a method in a class:
Java Code:public ArrayList<String> getMyList() { return myList; }
It also allows you to stub these things out when testing.
In essence, you want to be coding against the contract of a class (the interface), not the actual implementation of that contract.
The using class shouldn't care how the implementing class does its job, so long as it does its job.Please do not ask for code as refusal often offends.
** This space for rent **
Similar Threads
-
Interface Inheritance : create class that implements the interface
By Zulkifli_Rahman in forum New To JavaReplies: 1Last Post: 07-08-2012, 06:23 PM -
Initializing objects- nonstatic fields cannot be referenced from a static context
By Nazneen Ali in forum New To JavaReplies: 4Last Post: 07-19-2011, 02:30 PM -
The type XX cannot be resolved. It is indirectly referenced from required .class file
By futuros in forum New To JavaReplies: 1Last Post: 03-11-2011, 09:37 AM -
Objects not referenced in the sources
By krimen_sp in forum NetBeansReplies: 0Last Post: 12-30-2010, 04:31 PM -
class instantiation in referenced project causes ClassNotFoundException
By liorchaga in forum EclipseReplies: 12Last Post: 08-02-2010, 03:39 PM
Bookmarks