Today, we discussed the concept of constructors in Java. A constructor is a special method in a class that is used to initialize objects. It has the same name as the class and does not have any return type.
When an object is created, the constructor is called automatically. It is mainly used to initialize object-specific (non-static) variables. Every time an object is created, space is allocated in memory, and non-static variables are initialized using the constructor.
If we do not write any constructor in the class, the Java Virtual Machine (JVM) will provide a default constructor. The default constructor does not take any arguments and initializes the object with default values. There can be only one default constructor in a class.
Apart from the default constructor, we can also create parameterised constructors, also called argument constructors, which take arguments and initialize the object with specific values given during object creation.
Example
public class Store
{
static String storeName = "Tamil";
String prodName;
int price;
public Store(String s, int x) // constructor - argument constructor
{
prodName = s; // used for initializing object specific values (non-static)
price = x;
}
public static void main(String[] args)
{
System.out.println(Store.storeName); // static variable is printed using class name
Store prod1 = new Store("abc", 100); // object 1
System.out.println(prod1.prodName);
System.out.println(prod1.price);
Store prod2 = new Store("xyz", 1000); // object 2
System.out.println(prod2.prodName);
System.out.println(prod2.price);
}
}
Output
Tamil
abc
100
xyz
1000
Top comments (0)