aspose file tools*
The moose likes Java in General and the fly likes how to always instantiate object B when object A is instantiated Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "how to always instantiate object B when object A is instantiated" Watch "how to always instantiate object B when object A is instantiated" New topic
Author

how to always instantiate object B when object A is instantiated

Hendra Kurniawan
Ranch Hand

Joined: Jan 31, 2011
Posts: 239
look at this code:









I want everytime I instantiate Child1 or Child2 or any other class that extends Parent, that child class will always have an instantiated B. AFAIK, constructors are not inherited in java, so how do I do this without writting the same piece of code to specifically instantiate B in every child class? thanks
Bill Clar
Ranch Hand

Joined: Sep 21, 2006
Posts: 153

You can initialize "B" in the Parent's default constructor.

Stuart A. Burkett
Ranch Hand

Joined: May 30, 2012
Posts: 679
I must be missing something here, but why can't you just change line 3 of your Parent class to
Hendra Kurniawan
Ranch Hand

Joined: Jan 31, 2011
Posts: 239
@Bill: I thought constructors are not inherited?
@Stuart: never thought of that before. I'll try it out.

thanks
Stuart A. Burkett
Ranch Hand

Joined: May 30, 2012
Posts: 679
Hendra Kurniawan wrote:@Bill: I thought constructors are not inherited?

They're not, but all constructors have to call one of the constructors of their super class.
If you don't do it explicitly, the compiler adds a call to super() as the first line of your constructor.
Bill Clar
Ranch Hand

Joined: Sep 21, 2006
Posts: 153

Hendra Kurniawan wrote:@Bill: I thought constructors are not inherited?


They're not. I'm unsure of the exact verbage, but the default constructor of the Parent class is called unless a call to super(...) is made.



The above code won't compile:

Child.java:4: cannot find symbol
symbol : constructor Parent()
location: class Parent

Adding a call to the super constructor fixes this:

Hendra Kurniawan
Ranch Hand

Joined: Jan 31, 2011
Posts: 239
okay, thanks guys. will try it out. thanks again.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Bill Clar wrote:You can initialize "B" in the Parent's default constructor.

You mean no‑arguments constructor? You can’t do anything more than super(); in a default constructor.
Bill Clar
Ranch Hand

Joined: Sep 21, 2006
Posts: 153

Campbell Ritchie wrote:
Bill Clar wrote:You can initialize "B" in the Parent's default constructor.

You mean no‑arguments constructor? You can’t do anything more than super(); in a default constructor.


Yes, the no arguments constructor. My mistake.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to always instantiate object B when object A is instantiated