4

我是 OOP 的新手,我想知道如何设置一些不像 int、string、double 等的东西。

我有两个类,Foo 和 Bar,以及一些实例变量 如何设置 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

4 回答 4

3

与其他任何方法一样,创建 a 的实例Bar并将其设置在实例属性上。

您可以在构造函数中创建这些实例,将它们传递给构造函数,或使用 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());
    }

}
于 2012-09-06T01:13:07.060 回答
3

您需要Bar使用new运算符创建一个新实例,并将它们分配给您的成员变量:

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

参考:

于 2012-09-06T01:13:07.733 回答
1

如果要在默认构造函数中设置Bar,则必须实例化它。

这是使用new 运算符完成的。

Bar someBar = new Bar();

您还可以创建带参数的构造函数。

下面是如何创建一个将 String 作为参数的Bar构造函数:

class Bar {

    private String name;

    public Bar(String n) {
        name = n;
    }

}

以下是如何在Foo 的默认构造函数中使用新的Bar构造函数:

class Foo {

    private String name;
    private Bar theBar;

    public Foo() {
        name = "Sam";
        theBar = new Bar("Cheers");
    }

}

更聪明的是,您可以创建一个带有两个参数的新Foo构造函数:

class Foo {

    private String name;
    private Bar theBar;

    public Foo(String fooName, String barName) {
        name = fooName;
        theBar = new Bar(barName);
    }  

}
于 2012-09-06T01:41:02.730 回答
1

试试这个例子

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 等还有 person 这样的类

于 2012-09-06T04:13:04.997 回答