简体   繁体   English

如何访问在另一个类中定义的对象?

[英]How can I access an object defined in another class?

I have a class called Student, Of course this is not the entire code, I'm just trying to understand the concept.我有一个名为 Student 的类,当然这不是整个代码,我只是想了解这个概念。 I want to use the another obj in the User class which has college class obj created.我想在创建了大学类 obj 的 User 类中使用另一个 obj 。 The college class is the one that has the other class obj in it.大学班级是其中包含另一个班级 obj 的班级。 I have only done associations so far not inheritance so solutions related to associations will be helpful.到目前为止,我只做过关联而不是继承,因此与关联相关的解决方案会有所帮助。

public class College
{
  private Student[] student;
  private Teacher[] teacher;
  int count;
  public College()
  {
    student = new Student[9];
    teacher = new Teacher[9];
    count = 0;
  }

  public Student[] getStudent()
  {
    return student;
  }

  public void addStudent(Student inStudent)
  {
      student[count] = new Student(inStudent);
      count++;
  }

  public void setStudent(Student[] student)
  {
    this.student = student;
  }

  public Teacher[] getTeacher()
  {
    return teacher;
  }

  public void setTeacher(Teacher[] teacher)
  {
    this.teacher = teacher;
  }

  public boolean equals(Object inObj)
  {
    boolean isEqual = true;
    College inCollege = (College)inObj;

    if(student.length == inCollege.getStudent().length)
    { 
      for(int i = 0; i < student.length; i++)
      {
        if(!student[i].equals(inCollege.student[i]))
        {
            isEqual = false;
        }
      }
    }
    if((teacher.length == inCollege.getTeacher().length) )
    {
      isEqual = false;
      for(int i = 0; i < inCollege.getTeacher().length; i++ )
      {
        if(teacher[i].equals(inCollege.teacher[i]))
        { System.out.println("im in");
          isEqual = true;
        }
      }
    }
    return isEqual;
  }
}

You need to have public accessors (getters) for the private members to be accessed in other classes.您需要有public访问器(getter)才能在其他类中访问private成员。

Do it as follows:请按以下步骤操作:

import java.util.Scanner;

class Engine {
    String name;
    int year;
    String manufacturer;

    public Engine() {
    }

    public Engine(String name, int year, String manufacturer) {
        this.name = name;
        this.year = year;
        this.manufacturer = manufacturer;
    }

    // getters and setters of instance variables

    @Override
    public String toString() {
        return "Engine [name=" + name + ", year=" + year + ", manufacturer=" + manufacturer + "]";
    }
}

class Submarine {
    private String id;
    private Engine engine;

    public Submarine(String id, Engine engine) {
        this.id = id;
        this.engine = engine;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    public Engine getEngine() {
        return engine;
    }

    @Override
    public String toString() {
        return "Submarine [id=" + id + ", engine=" + engine + "]";
    }
}

class ShipStorage {
    private Submarine submarine;
    private Submarine[] submarines;

    public void setSubmarine(Submarine submarine) {
        this.submarine = submarine;
    }

    public Submarine getSubmarine() {
        return submarine;
    }

    public void setSubmarines(Submarine[] submarines) {
        this.submarines = submarines;
    }

    public Submarine[] getSubmarines() {
        return submarines;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        ShipStorage store = new ShipStorage();

        // Input submarines
        Submarine[] submarines = new Submarine[3];
        String id, name, manufacturer;
        int year;
        for (int i = 0; i < submarines.length; i++) {
            System.out.print("Enter the ID of the sumarine: ");
            id = in.nextLine();
            System.out.print("Enter the name of its engine: ");
            name = in.nextLine();
            System.out.print("Enter the manufacturing year of its engine: ");
            year = Integer.parseInt(in.nextLine());
            System.out.print("Enter the manufacturer's name of its engine: ");
            manufacturer = in.nextLine();

            submarines[i] = new Submarine(id, new Engine(name, year, manufacturer));
        }

        // Store submarines to ShipStorage
        store.setSubmarines(submarines);

        // Display submarines
        System.out.println("Displaying the data: ");
        for (Submarine submarine : store.getSubmarines()) {
            System.out.println(submarine);
        }
    }
}

A sample run:示例运行:

Enter the ID of the sumarine: 1
Enter the name of its engine: A
Enter the manufacturing year of its engine: 2010
Enter the manufacturer's name of its engine: X
Enter the ID of the sumarine: 2
Enter the name of its engine: B
Enter the manufacturing year of its engine: 2011
Enter the manufacturer's name of its engine: Y
Enter the ID of the sumarine: 3
Enter the name of its engine: C
Enter the manufacturing year of its engine: 2018
Enter the manufacturer's name of its engine: Z
Displaying the data: 
Submarine [id=1, engine=Engine [name=A, year=2010, manufacturer=X]]
Submarine [id=2, engine=Engine [name=B, year=2011, manufacturer=Y]]
Submarine [id=3, engine=Engine [name=C, year=2018, manufacturer=Z]]

Add a getter to Submarine:给 Submarine 添加一个 getter:

public Engine getEngine() {
     return engine;
}

And same thing to ShipStorage:和 ShipStorage 一样:

public Submarine getSubmarine() {
     return submarine;
}

Then use both of them in User:然后在 User 中同时使用它们:

Engine = store.getSubmarine().getEngine();

You have a lot of options to do this.你有很多选择来做到这一点。

  1. Turn private modifier to protected(if classes are in same package) or public of eng object in Submarine class(Do samething in ShipStorage class).However it ignores encapsulation.将私有修饰符转换为保护(如果类在同一个包中)或 Submarine 类中 eng 对象的公共(在 ShipStorage 类中做同样的事情)。但是它忽略了封装。
  public class Submarine
  {

    public Engine eng;
    public void Submarine ()
    {
      eng = new Engine ();
    }
  }

then use store.submarine[index].engine;然后使用 store.submarine[index].engine; statement.陈述。

  1. Create getter method to get engine instance in Submarine class.创建 getter 方法以获取 Submarine 类中的引擎实例。 Do same thing in ShipStorage class.在 ShipStorage 类中做同样的事情。
  public class Submarine
  {
    private Engine eng;
    public void Submarine ()
    {
      eng = new Engine ();
    }

    public Engine getEngine ()
    {
      return eng;
    }
  }

then use store.getSubmarineArr()[index].getEngine();然后使用 store.getSubmarineArr()[index].getEngine(); statement.陈述。

  1. You can add public static keyword in front of variable declaration(public static Engine eng;) if you want to access variable without initializing class.如果您想在不初始化类的情况下访问变量,您可以在变量声明前添加 public static 关键字(public static Engine eng;)。 However you have a sensible reason to use static keyword.但是,您有一个合理的理由使用 static 关键字。 Check use of static method, variable or class.检查静态方法、变量或类的使用。

For instance;例如;

Engine.eng

or或者

Engine.getEngine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM