Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

a simple thing of constructor  RSS feed

 
Jason.C. Wolfman
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A {
public A(String s) {
System.out.println(s);
}
}
class B {
A a1 = new A("a1"); //line1
}
class C extends B {
public C() {
A a2 = new A("a2");
}
public static void main(String[] args) {
new C();
}
}
the outputis
a1
a2
I don't understand why line1 will be ran.
It's not in class B's constructor, and it seems that a1 should not be printed out???
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let's ignore C for a sec...
In class B, a1 is a variable which is initialized by creating a new A. Java runs that initialization when you create a B, so if you just created a new B you'd see the A1 output. This happens even without a coded constructor in B. You might try "new B()" and see it work.
Now putting C back in the mix: C extends B, which means you get all the goodness of B including a member variable a1 and a1 gets initialized. You can imagine the compiler copied all the initialization instructions from B to C when you said "C extends B" (That's not really true, but it's a simple fantasy that works in simple cases.)
Does that help or hurt your understanding?
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!