当通过其他类构造函数在主方法中创建对象时访问对象属性
问题描述:
我有3个类测试,工厂和电视 - 工厂旨在创建电视(类包含在下面)。当通过其他类构造函数在主方法中创建对象时访问对象属性
如何访问或操作新的TV的属性,这是在Test Class的主要方法中创建的(通过由Test类中的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
}
}
答
你的问题是,你的厂级生产电视,但从来没有船舶他们的任何地方。
为了操纵一个物体,你需要一个对它的引用。只需将produceTV方法返回生产的电视。
public TV produceTV(int a, double b){
numberOfTV++;
return new TV(a,b);
}
现在您创建一个从未使用过的引用;编译器很可能会消除电视对象的创建。
您的'produceTv'方法应该*返回*新创建的电视。然后你可以有'TV tv = tvFactory.produceTV(2001,399);',之后你可以使用'tv'。 –
在'TV'类中添加getter和setter函数,并使用这些方法更改它们的值 –