If you want to install Bar in your default constructor, you will have to create it.
This is done using the new operator .
Bar someBar = new Bar();
You can also create constructors with parameters.
Here you can create a Bar constructor that takes a String parameter as a parameter:
class Bar { private String name; public Bar(String n) { name = n; } }
Here's how to use your new Bar constructor in the default constructor of Foo:
class Foo { private String name; private Bar theBar; public Foo() { name = "Sam"; theBar = new Bar("Cheers"); } }
To be even smarter, you can create a new Foo constructor that takes two parameters:
class Foo { private String name; private Bar theBar; public Foo(String fooName, String barName) { name = fooName; theBar = new Bar(barName); } }
source share