Computer Science

Start Free Trial

Create a Java class called "product" with three data elements: name, price per unit, and quantity. Use accessor and mutator methods, and at least three constructors, in the Main Java application. Call the product class to create at least three objects, each with different constructors. Calculate the cost of each product object and the total price and print out the data about the product objects.

The contents of the Java file Product.java are given below.

Expert Answers

An illustration of the letter 'A' in a speech bubbles

The class is pretty straightforward: it is public, and it contains three private members, three public constructors with different sets of parameters, three public accessors, and three public mutators. The file for this class should be named Product.java (the same name as the class name).

One more public member that one can add is the method that multiplies price by quantity to get the cost of the product.

eNotes Homework Help policy does not permit Educators to complete assignments for students, so I leave to you the file with main() function.

The contents of the file Product.java are as follows:

public class Product
{
// private member variables
private String name ;
private double price ;
private int quantity ;

// constructors
public Product ( ) // default constructor
{
name = "New Product" ;
price = 1.0 ;
quantity = 1 ;
}

// constructor that takes name only
public Product ( String name )
{
this.name = name ;
price = 1.0 ;
quantity = 1 ;
}

// constructor that takes data for all three members
public Product ( String name , double price , int quantity )
{
this.name = name ;
this.price = price ;
this.quantity = quantity ;
}

// accessors / mutators
public String getName ( )
{
return name ;
}

public double getPrice ( )
{
return price ;
}

public int getQuantity ( )
{
return quantity ;
}

public void setName ( String name )
{
this.name = name ;
}

public void setPrice( double price )
{
this.price = price ;
}

public void setQuantity( int quantity )
{
this.quantity = quantity ;
}
}

See eNotes Ad-Free

Start your 48-hour free trial to get access to more than 30,000 additional guides and more than 350,000 Homework Help questions answered by our experts.

Get 48 Hours Free Access
Approved by eNotes Editorial Team