Note: Please use
code tags when you post a piece of
Java code, so that the forum software can format it in a readable way.
Ok, I tried your code. The output is this:
First case:
init-ss-1: null
init-ss-2: init
ss****:blank
Second case:
init-ss-1: null
init-ss-2: init
ss****:init
So your question is why in the last line the outputs are different.
To understand why this is, you have to understand the order in which things are initialized when you create a new object. When you create a new object, the superclass part of the object is initialized first. So the constructor of abstract class A is called first. In that constructor, you call init(). Note that at the moment you call init(), the member variables of the subclass part (specifically, the member variable ss in class Test) is not yet initialized - you are calling it while the superclass is initializing, and when the subclass part is not yet initialized.
In init() you set ss to a value "init". Then init() returns to the constructor of the superclass, the superclass constructor returns and then Java initializes the subclass part. So Java then sets ss to the value "blank". You see?
The problem occurs because you are calling init() at the wrong moment - from the superclass constructor.
At the moment I'm working on a piece of software built upon a framework that our client has designed themselves. In this framework we have the exact same problem - the superclass that we're supposed to use for GUI objects also calls an init() method that we're supposed to override in our subclasses. In my opinion it is a design flaw to do something like this. Objects should be initialized in the constructor, because that's what the constructor is for. Inventing special init() methods like this is not a good idea.
[ March 09, 2007: Message edited by: Jesper Young ]