In below code I have some doubt in following line :
btn.addActionListener(this);
th= new Thread(this);
code :
public class Foo extends Applet implements Runnable,ActionListener
{
Button btn;
Thread th;
public void init()
{
btn=new Button("Click on me");
add(btn);
btn.addActionListener(this); // pass reference as this
th=null;
}
public void run()
{
int i=0;
while(i++<10)
{
try{
th.sleep(500);
showStatus(new Integer(i).toString());
}
catch(Exception e){}
}
}
public void actionPerformed(ActionEvent e)
{
if(th==null)
{
th= new Thread(this); // pass reference as this
th.start();
}
}
}
in Thread class constructor Thread(Runnable target) Allocates a new Thread object.
We can pass Runnable Target but I have passed this as parameter. I have implemented Runnable interface though it is possible
But again I have passed this as parameter In this case we can pass ActionListener target.
If we pass this as parameter in both the cases how It can get resolved.
I think this reference is targeting to reference of
1. Foo
2. Runnable
3. ActionListener
so how suitable reference is selected for method or constructor?.
You have a IS-A relationship :
FooIS-AAppletFooIS-ARunnableFooIS-AActionListenerWhen new object of type
Foois created ,Foowill be “selected reference” type. You have to cast to others if you want to have different type (from the selected list).As long as
FooIS-AApplet,RunnableandActionListener, the contract of the methods are fullfiled :btn.addActionListener(this);takesFoowhich IS-AActionListener,th= new Thread(this);takesFoowhich IS-ARunnable.