There was a Maryland programmer,
Who read the cert book until slumber,
Then after bit,
To show he got-it,
He wrote his own class modifier.
The classes were simple and frugal,
More code would not have been fruitful,
His job was to illustrate,
Not to obfuscate,
Small class sizes were much more useful.
He put in just enough print statements,
Not too many too few or too less,
But when it did run,
His brain from skull sprung,
Cuz his code was acting teh stoopids!
So he bought cheap beer and did drink it,
On his harsh code he thought "aww screw it",
But after much puking,
He submitted it thinking,
Perhaps Javaranch will help decipher it.
Here's the code:
class BaseClass{
private
String name;
void setName(String name) {
this.name = name;
}
String getName() {
return this.name;
}
BaseClass() {
System.out.println("Base constructor called on the sly");
}
BaseClass(String name) {
System.out.println("Base constructor directly called");
setName(name);
}
void describe(Integer j) {
System.out.println("BaseClass" + getName() + " " + j);
}
}
class ChildClass1 extends BaseClass{
ChildClass1(String s){
System.out.println("ChildClass1 constructor called");
setName(s);
}
void describe(Integer j) {
System.out.println("ChildClass1" + getName() + " " + j);
}
}
class ChildClass2 extends BaseClass{
ChildClass2(String s){
System.out.println("ChildClass2 constructor called");
setName(s);
}
void describe(Integer j) {
System.out.println("ChildClass2" + getName() + " " + j);
}
}
public class TestFor {
public static void main(String... args){
BaseClass[] bcArray = { new BaseClass("One"), new ChildClass1("Two"), new ChildClass2("Three") };
int j = 0;
for(BaseClass b : bcArray) {
if( b instanceof BaseClass)
b.describe(j);
if( b instanceof ChildClass1 )
b.describe(j);
if(b instanceof ChildClass2 )
b.describe(j);
j++;
}
}
}
And here's the output:
Base constructor directly called
Base constructor called on the sly
ChildClass1 constructor called
Base constructor called on the sly
ChildClass2 constructor called
BaseClassOne 0
ChildClass1Two 1
ChildClass1Two 1
ChildClass2Three 2
ChildClass2Three 2
Can anyone help expaly why the Base constructor isn't called after ChildClass2 is initialized?