Tuesday, May 23, 2006

Instance Initializer Blocks in Anonymous classes.

import java.io.*;

public class Check {

public static void main(String[] args) {
Clock c = new Clock();
c.call();
}

void result() {
System.out.println("Hello");
}
}

class Clock {

public void call() {
try{
Check ck = new Check() {
// FileInputStream fis = new FileInputStream("file.txt");

{
FileInputStream fis = new FileInputStream("file.txt");
}

void result() {
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.

In case of normal classes, the only checked exceptions allowed to be thrown by instance initializers are those that have been delcared to be thrown by each constructor. Furthermore, the class has to have at least one explicit constructor. Anonymous classes don't have explicit constructors so the rule that applies here is that their initializers can throw any exception without the need for declaring it.

*/

Instance Initializer Blocks in Normal Classes

import java.io.*;

class Checkep {

{
FileInputStream fis = new FileInputStream("file.txt"); System.out.println("instance block");
}

public static void main(String[] args) {
try {
Checkep c = new Checkep();
}catch(IOException ie) { }

System.out.println("main method");
}

Checkep() throws IOException {
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