Implement a class according to its UML class symbol: Product -name: String -pric
ID: 3826843 • Letter: I
Question
Implement a class according to its UML class symbol: Product -name: String -price: double -scanCode: int -numObjects: int = 0 +Product (String, double) +getName(): String +getScanCode: int +getPrice(): double +changePrice (double): void +getNumObjects(): int +getNumberInstock(): int The constructor shall take two parameters to initialise the name and price fields. The variable numObjects shall be incremented by the constructor every time a new object is instattiated. The scanCode is a 4-digit integer value 1000 +numObjects initialised by the constructor. Test the defined class with the following program: class TestProduct {public static void main (String[] args) {System.out.println ("There are " + Product.getNumberInStock() + "items"); Product pr1 = new Product ("Computer", 1500.0); System.out.println ("There are" + Product.getNumberInstock() + "items"); Product pr2 = new Product ("Printer", 600.0); Product pr3 = new Product ("Monitor", 240.0); System.out.println ("There are" + Product.getNumberInstock() + "items");Explanation / Answer
TestProduct.java
public class TestProduct {
public static void main(String[] args) {
System.out.println("There are "+Product.getNumberInStock()+" items");
Product pr1 = new Product("Computer", 1500.0);
System.out.println("There are "+Product.getNumberInStock()+" items");
Product pr2 = new Product("Printer", 600.0);
Product pr3 = new Product("Monitor", 240.0);
System.out.println("There are "+Product.getNumberInStock()+" items");
}
}
Product.java
public class Product {
private String name;
private double price;
private int scanCode;
private static int numObjects = 0;
public Product(String name, double price) {
this.name = name;
this.price = price;
numObjects++;
}
public String getName() {
return name;
}
public int getScanCode() {
return scanCode;
}
public int getNumObjects() {
return numObjects;
}
public void changePrice(double p){
price = p;
}
public double getPrice() {
return price;
}
public static int getNumberInStock() {
return numObjects;
}
}
Output:
There are 0 items
There are 1 items
There are 3 items
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.