Program to demonstrate Constructor Overloading in Java

This is a simple program to demonstrate constructor overloading in Java programming language.

Advertisements

The constructor is a special method that the same name as that of the public class. There are different methods of overloading the constructors.

This is a simple program to demonstrate the constructor overloading concepts and it is intended for beginners of  Java programming language.

Advertisements

We are using JDK 8u111 with Netbean IDE 8.2 installed on a windows 7 64-bit PC to compile and run this program.

Problem Definition

The constructor uses the same name as that of its public class. But the constructors can be different or overloaded based on the parameters. In the following program we specify 3 constructors with different type and number of parameters.

Program Code

class Cload{

    String pname;

    int qty;

    int price;

    Cload (int prodqty,String prodname, int prodprice)
    {

        pname=prodname;

        qty=prodqty;

        price=prodprice;

    }

    Cload(int q,String p1name)
    {

        pname=p1name;

        price = q;

        qty = price/10;

    }

    Cload(String ppname,int pprice)
    {

        pname= ppname;

        price = (int)(pprice - (0.1));

    }

    void print()
    {
        System.out.println("Product Name:" + pname);

        System.out.println("Quantity:" + qty);

        System.out.println("Price:" + price);

    }

public static void main(String args[])
{

    Cload prods = new Cload("apple",10);

    Cload prods1 = new Cload(200,"orange");

    prods.print();

    prods1.print();

}

}

Output – Java Constructor Overloading

Product Name:apple
Quantity:0
Price:9
Product Name:orange
Quantity:20
Price:200

Related Articles:-

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.