Is it possible to instantiate an interafce ?
Greeting all ,
please , can you explain when instantiating an interface is acceptable and reasonable ?
i'm asking due to with my pre knowledge that an interface can't be instantiate .
example :
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
moveSquare(e.getX(),e.getY());
}
});
Re: Is it possible to instantiate an interafce ?
Always read the API documentation - MouseAdapter is not an interface:
Quote:
This class exists as convenience
MouseAdapter (Java Platform SE 6)
Re: Is it possible to instantiate an interafce ?
yes i'm sorry and you are right i did provided a wrong example ...
what i mean is something like this
interface anInterface { void aMethod(); }
class myClass { anInterface A1 = new anInterface();
}
Re: Is it possible to instantiate an interafce ?
I'm not exactly sure whether the answer is exactly yes or no (* see edit below), but you can instantiate an anonymous object (The Java tutorial docs call these anonymous inner classes) which implements an interface:
Code java:
package com.javaprogrammingforums.domyhomework;
interface TheInterface
{
public void doSomething();
}
public class InstantiateAnInterface
{
public static void main(String[] args)
{
new TheInterface()
{
public void doSomething()
{
System.out.println("Wahey!");
}
}.doSomething();
}
}
... and of course you can write your own class that *implements* an interface
edit: helloworld922 (see below) is absolutely technically correct - the answer is 'no'. The fact that we typically always comply with a request from someone to give them an instance of MouseListener (rather than saying "actually that is impossible end of story") is no excuse for my prevarication.
Re: Is it possible to instantiate an interafce ?
yes , i will read about this concept " anonymous inner classes " it is new for me , and thank you very much Sean4u for ur responding :) .
Re: Is it possible to instantiate an interafce ?
You cannot directly instantiate abstract classes or interfaces, period. However, what you have there is an anonymous inner class, which happens to extend another class (in this case, it's the MouseAdapter class, which happens to be abstract).
Re: Is it possible to instantiate an interafce ?
Hi Learner,
It is impossible to instantiate an interface, but you can instantiate new objects of classes which derived from that interface. For example:
interface A { }
class B implements A { }
// WRONG: A a = new A();
// CORRECT:
A a = new B();// this is possible, since B implements A
This is something called polymorphism, that means the declared type is static, but the runtime object can be changed dynamically.
immutable objects
Re: Is it possible to instantiate an interafce ?
You can not instantiate Interface in any case. And the example is just anonymous class and it looks like you are initiating Interface.