Instance Initializer Blocks in Anonymous classes.
public static void main(String[] args) {
Clock c = new Clock();
c.call();
}
void result() {
System.out.println("Hello");
}
}
public void call() {
try{
Check ck = new Check() {
// FileInputStream fis = new FileInputStream("file.txt");
{
FileInputStream fis = new FileInputStream("file.txt");
}
System.out.println("Hello World!" );
}
};
ck.result();
}catch(Exception ie) { }
}
/*
"Instance initializers in annonymous classes can throw any uncaught checked exception."
The Constructor of FileInputStream produces FileNotFoundException which is an checked exception.
This is an example of the above statement. This compiles fine.
*/
Instance Initializer Blocks in Normal Classes
import java.io.*;
class Checkep {
{
FileInputStream fis = new FileInputStream("file.txt"); System.out.println("instance block");
}
try {
Checkep c = new Checkep();
}catch(IOException ie) { }
System.out.println("main method");
}
System.out.println("constructor");
}
}
/*
Refer Khalid Mugal Book page: 341
In case of normal classes, the execution of instance initializer blocks can result in uncaught checked exception. The only checked exceptions allowed to be thrown by instance initializers are those that have been delcared to be thrown by every constructor in th class. Furthermore, the class has to have at least one explicit constructor. Anonymous classes don't have explicit constructors so the rule that applies in anonymous classes is that their instance initializers can throw any exception without the need for declaring it.
*/
0 Comments:
Post a Comment
<< Home