Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating an instance of a class type variable

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 = "";
    }
}
like image 207
Dog Avatar asked Feb 19 '23 06:02

Dog


2 Answers

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());
    }

}
like image 191
Dave Newton Avatar answered Feb 27 '23 00:02

Dave Newton


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();
}

References:

  • Classes and Objects
  • Creating Objects
like image 24
João Silva Avatar answered Feb 26 '23 23:02

João Silva