011-003-007

Constructor: Overloading

Medium

Problem Description

constructor: Overloading

In this problem, you will create a program that defines two overloaded constructors for a Product class—one accepting only a name and one accepting both name and price—reads input via Scanner, instantiates objects with each constructor, and displays the results to standard output.

Learning Objective: Define multiple constructors to enable context-appropriate initialization

Overview

Define two constructors for the Product class. One accepts only a name and initializes price to 0, the other accepts both name and price.

Specifications

  • Product class fields: name (String type), price (int type)
  • Constructor 1: Takes only name as argument, initializes price to 0
  • Constructor 2: Takes both name and price as arguments, initializes both
  • getInfo method: Returns string in format "Product: [name], Price: [price]"
  • In main method, read input via Scanner, create objects using both constructors and output information

Input Format

name of product 1
name of product 2
price of product 2

Output Format

Product: [name1], Price: 0
Product: [name2], Price: [price2]

Sample Input/Output

Input:
Pen
Notebook
300

Output:
Product: Pen, Price: 0
Product: Notebook, Price: 300

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up