InterviewSolution
| 1. |
Can A Method Which Is Not In The Definition Of The Superclass Of An Anonymous Class Be Invoked On That Anonymous Class Reference? |
|
Answer» No. As the REFERENCE variable type of the anonymous class will be of superclass which will not know about any method defined inside the anonymous class and HENCE the compilation will FAIL. class Superclass { void DOSOMETHING() { System.out.println ("In the Super class"); } } class has Anonymous { Superclass anon = NEW Superclass () { void doSomething() { System.out.println("In the Anonymous class"); } void doStuff() { System.out.println ("An Anonymous class method not present in superclass"); } }; public void doIt() { anon. DoSomething(); // legal superclass has this method anon. DoStuff(); // Not legal } } The above code will not compile as the superclass does not know about the anonymous class method doStuff (). No. As the reference variable type of the anonymous class will be of superclass which will not know about any method defined inside the anonymous class and hence the compilation will fail. class Superclass { void doSomething() { System.out.println ("In the Super class"); } } class has Anonymous { Superclass anon = new Superclass () { void doSomething() { System.out.println("In the Anonymous class"); } void doStuff() { System.out.println ("An Anonymous class method not present in superclass"); } }; public void doIt() { anon. DoSomething(); // legal superclass has this method anon. DoStuff(); // Not legal } } The above code will not compile as the superclass does not know about the anonymous class method doStuff (). |
|