[英]Accessing object properties when object is created in main method via other class constructor
I have 3 classes Test, Factory and TV - Factory is aimed to create TVs (classes are included below).我有 3 个类 Test、Factory 和 TV - Factory 旨在制作电视(下面包含类)。
How can I access or manipulate properties of new TV, that was created in main method of Test Class (via TV class constructor invoked by Factory method in Test 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
}
}
Your problem is that your Factory class produces TVs but never ships them anywhere.您的问题是您的工厂类生产电视但从不将它们运送到任何地方。
In order to manipulate an object, you need a reference to it.为了操作一个对象,你需要一个对它的引用。 Simply have the produceTV method return the TV that is produced.只需让 produceTV 方法返回制作的电视。
public TV produceTV(int a, double b){
numberOfTV++;
return new TV(a,b);
}
Right now you create a reference that is never used;现在您创建了一个从未使用过的引用; most likely the compiler will eliminate the TV object creation.编译器很可能会消除 TV 对象的创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.