Reputation: 605
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 = "";
}
}
Upvotes: 4
Views: 6989
Reputation: 878
Try this example
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//getters and setters
}
public class Student {
private String school;
private Person person;
public Student(Person person, String school) {
this.person = person;
this.school = school;
}
//code here
}
class Main {
public static void main(String args[]) {
Person p = new Person("name", 10);
Student s = new Student(p, "uwu");
}
}
String , Integer, Double etc. also classes like person
Upvotes: 1
Reputation: 22692
If you want to set a Bar in your default constructor, you'll have to instantiate it.
This is done using the new operator.
Bar someBar = new Bar();
You can also create constructors with parameters.
Here's how you would create a Bar constructor that takes a String as a parameter:
class Bar {
private String name;
public Bar(String n) {
name = n;
}
}
Here's how to use your new Bar constructor in Foo's default constructor:
class Foo {
private String name;
private Bar theBar;
public Foo() {
name = "Sam";
theBar = new Bar("Cheers");
}
}
To be even more clever, you could 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);
}
}
Upvotes: 1
Reputation: 160311
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());
}
}
Upvotes: 3
Reputation: 91349
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();
}
Upvotes: 3