• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pls help- write a code with anonymos class, indicate with a comment line in the code

 
kaffo lekan
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Please, write a code for me showing the use of an anonoymos class , please indicate with comment showing it.
 
Vegad Arvind
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Here the code and explanation from Exam cram mock test

In the following code for a class in which methodA has an inner class
1. public class Base {
2. private static final int ID = 3; //final variable
3. public String name; // public variable
4. public void methodA( int nn ){ //nn is arg not final
5. final int serialN = 11; //final variable
6. class inner { //innner class start here
7. void showResult(){
8. System.out.println( "Rslt= " + XX );
9. }
10. } // end class inner
11. new inner().showResult();
12. } // end methodA
13. )
which variables would the statement in line 8 be able to use in place of XX? [Check all correct answers]
A) The int ID in line 2
B) The String name in line 3
C) The int nn in line 4
D) The int serialN in line 5
Answer
A is correct: The int ID in line 2
B is correct: The String name in line 3
D is correct: The int serialN in line 5
Explanation Answers a, b, and d are correct. Answers a and b are correct because inner classes can access any static or member variable in the enclosing class. Answer d is correct because, although it is a local variable, it is declared final. Answer c is incorrect because the local variable nn is not declared final. This special usage of the keyword final causes the compiler to provide storage for this variable in a permanent location. This is necessary because an inner class object created in a method may outlive the method.

Hope it will help

Best Regards
Avi
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kaffo,
I am not sure what question Vegad was answering, but here is an example of using an anonymous class to override a single method. This is most useful when writing UI code and using listener adapters.

Regards,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic