Hi,
Q1 - Why this class does not print "Anonymous class" and 100.It just prints main$class2 followed by 101.?
U r creating instance of Anonymous class , but no where assigning to a reference.
------
Q2 - How it will print "Anonymous class" and 100?
We can change ret() method in class2 as below.
int ret()
{
System.out.println(this.getClass());
class1 obj=new class1(){ public int ret()
{
System.out.println("Anonymous class");
return k;
}
};
return obj.ret();
}
--------------------------------
Q3Can we define new methods in 'Anonymous' classes.If not. Why?
We can define new methods.But we will not be able to call it from outside as it is referring through its Parent classes (or interfaces).
Fallowing code is possible , but we should not fallow it.
Here , i have just defined one explicit method called Try() in Anonymous class and i called it from outside.It seems bo be very cryptic
(new class2(){
public int ret()
{
System.out.println("Anonymous class");
Try();
return k;
}
public int Try()
{
System.out.println("Inside Try
method");
return 420;
}
}).Try();
Hope i cleared ur questions.
----------
Prashant