Constructor in java
**Constructor will not have any return data type**
**Constructor is usefull for initializing specific
variables**
**A constructor in java is a special method that is used to
initialize object**
**The constructor is called when an object of a class is
created**
Usins constructor
Ex program:
class Dmart
{
String product_name;
int price;
int discount;
public Dmart(String product_name, int price, int discount) //parameterist constructor
{
this.product_name=product_name;
this.price=price;
this.discount=discount;
}
public static void main(String[] args) //main method
{
Dmart shop = new Dmart("milkbiscuit",25,5);
shop.sh();
}
public void sh() //method def or methoid body
{
System.out.println("product name: "+product_name );
System.out.println("product price: "+price);
System.out.println("product discount: "+discount );
}
}
Top comments (0)