【问题标题】:Accessing object properties when object is created in main method via other class constructor通过其他类构造函数在主方法中创建对象时访问对象属性
【发布时间】:2017-12-15 12:22:01
【问题描述】:

我有 3 个类 Test、Factory 和 TV - Factory 旨在创建电视(以下包括类)。

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

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();

    }
}

【问题讨论】:

  • 您的produceTv 方法应该返回新创建的电视。然后你可以拥有TV tv = tvFactory.produceTV(2001, 399);,之后你可以使用tv
  • TV 类中添加getter 和setter 函数并使用这些方法更改它们的值

标签: java object constructor main


【解决方案1】:
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 

    }
}

【讨论】:

    【解决方案2】:

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

    为了操作一个对象,你需要一个对它的引用。只需让 producerTV 方法返回生成的电视即可。

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

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

    【讨论】: