Constructor:
Constructor is method used to initialize object specific values to variables. JVM have default constructor.
Why use constructor?
- Each object gets initialized properly when it’s created.
- Helps reduce code repetition.
Characteristics:
- Constructor name as same as class name.
- No return type required.
- Automatically called when object is created.
- Initialize object specific values to variable.
Types of Constructor:
1. Default Constructor:
- A constructor with no parameters.
- If you don’t write any constructor, Java provides one by default.
Program for Default Constructor:
class Car {
Car() {
System.out.println("Car is created");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
}
}
Output:
Car is created
2. Argument Constructor:
- Constructor that takes arguments to initialize the object with specific values.
Program for Argument Constructor:
public class Market
{
static String marketName = "Nehru";
String prodname;
int price;
public Market(String s, int i)
{
System.out.println("I'm constructor");
prodname = s;
price = i;
}
public static void main(String[] args)
{
Market prod1 = new Market("abc",100);
Market prod2 = new Market("xyz",1000);
System.out.println(prod1.prodname);
System.out.println(prod2.prodname);
System.out.println(prod2.price);
}
}
Output:
I'm constructor
I'm constructor
abc
xyz
1000
Top comments (0)