| Author |
Doubt
|
sangeetha raj
Greenhorn
Joined: Feb 23, 2012
Posts: 16
|
|
Hi All,
I have a doubt in this program
1)Since here class A is abstract , we can't instantiate it ,so line 5 will cause compile time error.. (or)
2)Since line 9 is unreachable , it will cause compile error
Which one will be the answer..Because , in Examlab mock test , they have given option 2 is the answer..Please explain me..
Thanks,
SR
[HENRY: Added Code tags]
|
 |
Sahil Ji
Greenhorn
Joined: Apr 04, 2012
Posts: 6
|
|
[HENRY: Hijack question deleted]
|
 |
Anayonkar Shivalkar
Bartender
Joined: Dec 08, 2010
Posts: 1295
|
|
Hi sangeetha raj,
Please UseCodeTags.
Now, coming to your question, what code does is - it creates an anonymous class which IS-A 'A'.
If you are unaware of what inner-class is, then you should read about it and you'll come to know why there's no compile time error at line 5.
Compiler will give error saying line 9 is unreachable.
Secondly, please use meaningful subject to your question/post. It will give some idea to visitors of the forum.
I hope this helps.
|
Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD)
|
 |
sangeetha raj
Greenhorn
Joined: Feb 23, 2012
Posts: 16
|
|
Hi Anayonkar,
Thanks for the clarification..
|
 |
Arvind Darwin
Greenhorn
Joined: Mar 05, 2012
Posts: 10
|
|
sangeetha raj wrote:
[code = java]
A a=new A(){ //line 5
public void start() throws ArithmeticException{
System.out.print(1);
try{
System.out.print(2);
throw new ArithmeticException();
System.out.print(3);//line 9 unreachable
}catch(Exception e){
System.out.print(4);
}finally{
System.out.print(5);
}
}
};
[/code]
Thanks,
SR
[HENRY: Added Code tags]
Line 5 is not incorrect because abstract class A is not instantiated here.
Anonymous inner class, which is unnamed, and inherits from A and overrides start().
Since anonymous inner class has overridden the abstract start() method of class A, its no longer abstract and can thus be instantiated.
So option 2 is the correct answer.
Read K&B chapter 8 on Inner classes for more insight.
|
 |
Anayonkar Shivalkar
Bartender
Joined: Dec 08, 2010
Posts: 1295
|
|
sangeetha raj wrote:Hi Anayonkar,
Thanks for the clarification..
You are welcome.
|
 |
 |
|
|
subject: Doubt
|
|
|