Reputation: 23
I have 3 classes Test, Factory and TV - Factory is aimed to create TVs (classes are included below).
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();
}
}
Upvotes: 2
Views: 1009
Reputation: 3392
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.
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.
Upvotes: 0
Reputation: 3349
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
}
}
Upvotes: 2