我有 3 个类 Test、Factory 和 TV - Factory 的目的是创建 TV(下面包含类)。
如何访问或操作在测试类的主方法中创建的新电视的属性(通过测试类中的工厂方法调用的电视类构造函数)。
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
}
}
关于java - 通过其他类构造函数在主方法中创建对象时访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45034532/