使用在另一个Class的main方法中创建的实例

问题描述 投票:-1回答:2

我刚刚开始使用Java并遇到了一个问题:

假设我想要3个类,一个叫做“汽车”,一个是“数据库”,另一个是后来用来做事情的GUI(Jframe-Form,Swing):

public class Cars {
    int nummer;
    String name;

    //lets just say i have 10 differnet types from 0  - 9 and every type has 
    // a different priceclass between 1 and 10 to make things simple

    public int[] types = new int[10];

    public Cars(int nr, String na) {
        this.nummer = nr;
        this.name = na;

我现在想要在某种数据库中创建和保存汽车,不知道如何在Java中最有效地做到这一点所以我只是创建了这样一个类:

public class Beispieldatenbank {

    public Cars[] c;

    public Beispieldatenbank (Cars[] c) {
        this.c = c;
    }

    public int getLengthc() {
        return(this.c.length);
    }

现在我想创建一个包含几辆汽车的数据库,并为其分配价格类型。

public static void main(String[] args) {
    Cars[] c1 = new Cars[100];
    Beispieldatenbank Beispieldatenbank1 = new Beispieldatenbank(c1);

    Cars Audi = new Cars(1, "Audi");
    Beispieldatenbank1.c[1] = Audi;
    Audi.type[0] = 1; //So the 0th type-Audi shall be in price class "1"
            Audi.types[1] = 3; //similarly...


    Cars BMW = new Cars(2, "BMW");
    Beispieldatenbank1.c[2] = BMW;
    BMW.type[0] = 5;

    etc...

我希望“Beispieldatenbank1”成为唯一的,可公开访问的“Beispieldatenbank”实例,现在我的GUI中:

           JButton btnEingabe = new JButton("Eingabe");
    btnEingabe.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String s = textField.getText();
            for(int i = 1, i < *Beispieldatenbank1.c.length()*, i++){
                ...              

我现在想检查输入是否与其中一辆车匹配,那么看看是否输入了“Audi”但是:

我在另一个(GUI)类,我的Beispieldatenbank1无法访问!

这是因为“Beispieldatenbank1”只是稍后在“Beispieldatenbank”的主要方法中创建的,因此在我的GUI的actionPeformed中找不到/不存在?我认为既然“Beispieldatenbank1”是公开的,那么所有其他课程都可以访问它吗?如何解决这个问题,轻松实现这个数据库?是什么原因它不存在/可访问?

java class public instances
2个回答
0
投票

public类意味着您可以从任何其他类引用它。 这并不意味着可以在没有变量引用的情况下访问此公共类的所有实例。这没有任何意义,因为我们无法区分不同类的实例。

你的Gui类应该在一个字段中存储在Beispieldatenbank方法中创建的main()实例


0
投票

我希望“Beispiel Datenbank1”成为唯一可公开访问的“Beispiel Datenbank”实例

如果您希望可以访问该字段,则需要该字段

private static Beispieldatenbank Beispieldatenbank1;

public static void main(String[] args) {
    Cars[] c1 = new Cars[100];
    Beispieldatenbank1 = new Beispieldatenbank(c1);

    // now you can access the variable class-wide

您需要“单例模式”才能使该类的一个实例成为可能

我在另一个(GUI)类,我的Beispieldatenbank1无法访问!

无论何时构建GUI类,都需要通过构造函数或某些setter方法传递变量

另外,请不要将变量名称大写

© www.soinside.com 2019 - 2024. All rights reserved.