N Sam wrote:Thanks for posting this code. I have a question on line 82 & 83:
This seems to declare a static variable called myStaticB, but its type is B. Coming inside the declaration of class B, this seems to have a recursive definition. Obviously this is syntactically correct, but the recursive look is causing confusion to me. Can someone explain this piece of code ?
You may be over thinking this one. It is just declaring myStaticB as a static reference variable of type B. It is probably just in there to demonstrate when static variables get initialized. It only gets used on line 11:
where it is assigned to a local reference variable, which, unless I'm wrong, doesn't really do anything, since myStaticB would initialize with a default value of null, b1 was explicity declared as null, so assigning myStaticB to b1 they are both still null. See, confusing. Just understand that it is initializing a static reference variable of type B.
N Sam wrote:
The other line of code that confuses me is line 26
How come this call to the constructor ends up calling 2 constructors of class A ? The printout shows
I can understand all the output until then, and i see that first this code would call public B(string s). How come the empty constructor of A gets called from here ? Is this because of extending the base class ? I am not upto reading about inheritance in java , but understand the basic principles of inheritance.
It's all about the constructors. Calling the B constructor that takes a string "b", calls this() for the no-arg B constructor, which the compiler will insert super() as the first line since there is no super() or this() already there. So super() calls the superclass constructor, in this case the no-arg constructor of A, which has a this("s") which calls the A constructor that takes a string. Once you study constructors more it will make more sense.