I'm new to OOP and I was wondering how to set something that is not like int, string, double etc.
I have two classes, Foo and Bar, and some instance variables How can I set the Bar type instance variables?
public class Foo
{
//instance variables
private String name;
Bar test1, test2;
//default constructor
public Foo()
{
name = "";
//how would I set test1 and test 2?
}
}
public class Bar
{
private String nameTest;
//constructors
public Bar()
{
nameTest = "";
}
}
Same way as anything else, create an instance of a Bar
and set it on the instance property.
You can create those instances in a constructor, pass them to a constructor, or set with a setter:
public class Foo {
private Bar test1;
public Foo() {
test1 = new Bar();
}
public Foo(Bar bar1) {
test1 = bar1;
}
public void setTest1(Bar bar) {
test1 = bar;
}
public static void main(String[] args) {
Foo f1 = new Foo();
Foo f2 = new Foo(new Bar());
f2.setTest1(new Bar());
}
}
You need to create a new instance of Bar
, using the new
operator, and assign them to your member variables:
public Foo() {
name = "";
test1 = new Bar();
test2 = new Bar();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With