Creating an instance of a class type variable

I am new to OOP and I was wondering how to install something that doesn't look like int, string, double, etc.

I have two classes: Foo and Bar, and some instance variables. How to set instance variables of type Bar?

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 = ""; } } 
+4
source share
4 answers

Just like anything else, create an instance of Bar and set it in the instance property.

You can create these instances in the constructor, pass them to the constructor, or set them using 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()); } } 
+3
source

You need to create a new instance of Bar using the new operator and assign them to member variables:

 public Foo() { name = ""; test1 = new Bar(); test2 = new Bar(); } 

References:

+3
source

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); } } 
+1
source

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., as well as classes such as human

+1
source

Source: https://habr.com/ru/post/1432608/


All Articles