What is constructor: It is a method in Java that is used to initialize objects. The constructor is called when an object of a class is created. Non-static variables belong to an object, so constructors initialize them.
Characteristics of constructor:
- A constructor has the same name as the class.
- It does not have a return type, not even void.
- It can accept parameters to initialize object properties.
Ex:
class Shop{
static String Shop_name = "Vidya";
String prod_name;
int price;
int quantity;
public Shop(String a, int i, int j){
this.prod_name = a;
this.price = i;
this.quantity = j;
}
public static void main(String[] args){
Shop prod1 = new Shop("abc",50,2);
Shop prod2 = new Shop("xyz",500,4);
System.out.println("Is this a constructor");
System.out.println("Product name: " + prod1.prod_name + " Price: " + prod1.price + " Quantity: " + prod1.quantity);
System.out.println("Product name: " + prod2.prod_name + " Price: " + prod2.price + " Quantity: " + prod2.quantity);
}
}
Output:
Is this a constructor
Product name: abc Price: 50 Quantity: 2
Product name: xyz Price: 500 Quantity: 4
Constructor overloading: It is a feature in Java where a class can have multiple constructors with different:
a) Number of parameters
b) Types of parameters
c) Order of parameters
Top comments (0)