通过其他 class 构造函数在 main 方法中创建对象时访问对象属性

Accessing object properties when object is created in main method via other class constructor

我有 3 个 classes Test、Factory 和 TV - Factory 旨在制造电视(下面包含 classes)。

我如何访问或操作在测试 Class 的主要方法中创建的新电视的属性(通过测试 class 中工厂方法调用的电视 class 构造函数) .

public class TV {

    private int productionYear;
    private double price;

    public TV (int productionYear, double price){
        this.productionYear = productionYear;
        this.price = price;
    }

}

public class Factory {

    public static int numberOfTV = 0;


    public void produceTV(int a, double b){
        TV tv = new TV(a,b);
        numberOfTV++;
    }


    public void printItems(){
        System.out.println("Number of TVs is: " + numberOfTV);

    }
}

public class Test {

    public static void main(String[] args) {

        Factory tvFactory = new Factory();
        tvFactory.produceTV(2001, 399);
        tvFactory.printItems();

    }
}
public class TV {

    private int productionYear;
    private double price;

    public TV(int productionYear, double price) {
        this.productionYear = productionYear;
        this.price = price;
    }

    public int getProductionYear() {
        return productionYear;
    }

    public void setProductionYear(int productionYear) {
        this.productionYear = productionYear;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}

public class Factory {

    public static int numberOfTV = 0;


    public TV produceTV(int a, double b) {
        TV tv = new TV(a, b);
        numberOfTV++;
        return tv;
    }


    public void printItems() {
        System.out.println("Number of TVs is: " + numberOfTV);

    }
}

public class Test {

    public static void main(String[] args) {

        Factory tvFactory = new Factory();
        TV tv = tvFactory.produceTV(2001, 399);
        tvFactory.printItems();

        // Do manipulation with tv reference here 

    }
}

您的问题是您的工厂 class 生产电视但从未将它们运送到任何地方。

为了操作对象,您需要引用它。只需使用 produceTV 方法 return 制作的电视。

public TV produceTV(int a, double b){
  numberOfTV++;
  return new TV(a,b);      
}

现在您创建了一个从未使用过的引用;编译器很可能会消除 TV 对象的创建。