Java Constructors
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes
class Shop{
static String shopName="Amutham Stores"; //class variable or field
String product_name; //instance variables or fields
int price;
public Shop(){
System.out.println("Welcome to "+shopName); //default constructor
}
public Shop(String product_name,int price){ //local variables
this.product_name=product_name; //parameterized constructor
this.price=price;
System.out.println("Product name : "+ product_name +"|| Price :" +price);
}
}
class Main {
public static void main(String[] args) {
Shop shop=new Shop();
Shop product1=new Shop("soap",30);
}
}
Note that the constructor name must match the class name, and it cannot have a return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.
Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.
Shop(String product_name,int price){
}
Java this Keyword
The this keyword in Java refers to the current object in a method or constructor.
The this keyword is often used to avoid confusion when class attributes have the same name as method or constructor parameters.
You can also use this() to call another constructor in the same class.
This is useful when you want to provide default values or reuse initialization code instead of repeating it.
Top comments (0)