Features of a Constructor
🔹 Automatically called when an object is created.
🔹 Has the same name as the class.(Instead of giving another name java consider it method and ask a return type)
🔹 Does not have a return type.
🔹 Used to initialize object specific values.
Types of Constructors
- Default Constructor (Implicit)
🔹 If you do not write any constructor in your class, the Java compiler automatically inserts a blank, no-argument constructor during compilation.
🔹 This constructor keeps by Java virtual Machine.
2.No-Argument Constructor (Explicit)
🔹 A constructor written by the programmer with no parameters.
🔹 This constructor is created by user.
public MobilePhone(){
System.out.println("No arguments Constructor");
}
3.Parameterized Constructor
🔹 A constructor that accepts parameters to initialize objects with specific values.
public MobilePhone(String name,int price,int battery){
this.name = name;
this.price = price;
this.battery = battery;
}
Constructor Overloading
🔹 Constructor overloading is the process of defining two or more constructors in the same class with different parameter lists.
🔹 The compiler decides which constructor to call, based on the number or type of arguments passed when creating an object.
public MobilePhone(String name,int battery){
this.name = name;
this.battery = battery;
}
Code example
public class MobilePhone
{
String name;
int price;
int battery;
public MobilePhone(){
System.out.println("No arguments Constructor");
}
public MobilePhone(String name,int price,int battery){
this.name = name;
this.price = price;
this.battery = battery;
}
public MobilePhone(String name,int battery){
this.name = name;
this.battery = battery;
}
public static void main(String[] args)
{
// No argument constructor
MobilePhone brand = new MobilePhone();
//Parameterized Constructor
MobilePhone brand1 = new MobilePhone("Samsung s25 ultra",120000,5000);
MobilePhone brand2 = new MobilePhone("Realmep4 power",28000,10000);
//Constructor overloading(Two parameters)
MobilePhone brand3 = new MobilePhone("Vivo t5x",7200);
System.out.println("BrandName :" + brand1.name);
System.out.println("Price :" + brand1.price);
System.out.println("BrandName :" + brand2.name);
System.out.println("Price :" + brand2.price);
System.out.println("Battery :" + brand2.battery);
System.out.println("BrandName :" + brand3.name);
System.out.println("Battery :" + brand3.battery);
}
}

Top comments (0)