Marcos Luna
Posts: 1
Nickname: marcosluna
Registered: Apr, 2012
|
|
Re: what is the need of Constructor in Interface
|
Posted: Apr 25, 2012 11:06 PM
|
|
Kind of late but if it still helps someone.
An interface cant be instatiated, it just defines the methods a class must implement. So to be short if you have the interface
interface MyInterface { void doSomething(int x); }
the implementer class must be
class MyClass impmelents MyInterface {
public MyClass() { /* do what you want on contructor or define additional constructors */ }
void doSomenthing(int x) { //implement what you need here }
//add aditional methos if wanted
}
Then you can do a new instance of MyClass with
MyClass obj1 = new MyClass(); //do something with obj1
And because the interface specify what an object can do, you also can do the following
MyInterface simpleObject2 = new MyClass();
You can assign a variable of type MyInterface with an object instatiated from the implementation class. just remember that this will only give you access to what the Inteface defines, sometimes it helps to manage simpler objects in your code.
|
|