abstract class Abs { private int i; public abstract void first(); { // What these three lines specifies and when it will be executed System.out.println("in first");
} }
Please help me. What ie meant by Instance Initializer here.
Vaibhav Chauhan
Ranch Hand
Joined: Aug 16, 2006
Posts: 115
posted
0
if you make a subclass of class Abs, and make an object of the subclass then initializer in class Abs gets called as
try this code:
output is: in first in second in SubClass constructor
It is the block which will be executed before the constructor when object of a class type is create. but if there is static{} block present in the class type then it will be executed first time for first object and will not be executed for second object.
class hai{ static{ System.out.println("Iam in static block"); } { System.out.println("Iam in init block"); } } class din{ public static void main(String s[]) { System.out.println("Hello"); hai h=new hai(); hai hello=new hai(); } }
output:
Hello Iam in static block Iam in init block Iam in init block
Kaarthick Ramamoorthy
Greenhorn
Joined: Sep 01, 2006
Posts: 23
posted
0
Thanks.
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
It is important to realize that the instance initializer(s) are executed first no matter which constructor is executed. So you can use them for common initialization code. [ September 04, 2006: Message edited by: Barry Gaunt ]
If I understand correctly, in the above code they are creating the anonomous inner class. The code present inside the scope is the constuctor of the inner class without any name (ie., anonymous). What is not clear to me is when this inner class is defined static, how all the instance of the outer class refer to the same instance of the inner class. That is, conceptually, all the different objects are instantiating the same inner class.
bing marquez
Greenhorn
Joined: Aug 06, 2006
Posts: 11
posted
0
Hi Mahantesh
No, those are not anonymous inner classes. They are static blocks and init blocks as explicitly stated. For the exam, one way of spotting anonymous inner class is that following the definition of "new Class()" is an opening curly brace, instead of the usual ";". Then at the end of the closing curly brace, you'll find the semicolon instead "};"
For example:
Or if the anomymous class is argument defined:
In which case the semicolon is after the closing parenthesis "});". [ September 04, 2006: Message edited by: bing marquez ]