Logo

dev-resources.site

for different kinds of informations.

Java Constructors

Published at
1/5/2025
Categories
java
beginners
fullstack
payilagam
Author
neelakandan_ravi_2000
Author
21 person written this
neelakandan_ravi_2000
open
Java Constructors

Java Constructors:

Java constructors or constructors in Java is a terminology used to construct something in our programs. 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.

What are Constructors in Java?:

In Java, a Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called.

Understanding how to effectively use constructors can significantly improve your Java programming skills, especially when you’re dealing with complex applications. It’s crucial to grasp the nuances of constructors to build scalable and maintainable software.

Example of Java Constructor:

// Driver Class
class Geeks {

    // Constructor
    Geeks()
    {
        super();
        System.out.println("Constructor Called");
    }

    // main function
    public static void main(String[] args)
    {
        Geeks geek = new Geeks();
    }
}
Enter fullscreen mode Exit fullscreen mode

** How Java Constructors are Different From Java Methods?**

1.Constructors must have the same name as the class within which it is defined it is not necessary for the method in Java.
2.Constructors do not return any type while method(s) have the return type or void if does not return any value.
3.Constructors are called only once at the time of Object creation while method(s) can be called any number of times.

When Java Constructor is called?

Each time an object is created using a new() keyword, at least one constructor (it could be the default constructor) is invoked to assign initial values to the data members of the same class. Rules for writing constructors are as follows:

1.The constructor(s) of a class must have the same name as the class name in which it resides.
2.A constructor in Java can not be abstract, final, static, or Synchronized.
3.Access modifiers can be used in constructor declaration to control its access i.e which other class can call the constructor.

Types of Constructors in Java(TBD)

Now is the correct time to discuss the types of the constructor, so primarily there are three types of constructors in Java are mentioned below:

Image description
3.copy constructor

1. Default Constructor in Java

A constructor that has no parameters is known as default constructor. A default constructor is invisible. And if we write a constructor with no arguments, the compiler does not create a default constructor. It is taken out. It is being overloaded and called a parameterized constructor. The default constructor changed into the parameterized constructor. But Parameterized constructor can’t change the default constructor. The default constructor can be implicit or explicit.

Implicit Default Constructor: If no constructor is defined in a class, the Java compiler automatically provides a default constructor. This constructor doesn’t take any parameters and initializes the object with default values, such as 0 for numbers, null for objects.

2. Parameterized Constructor in Java

A constructor that has parameters is known as parameterized constructor. If we want to initialize fields of the class with our own values, then use a parameterized constructor.

** 3. Copy Constructor in Java**(TBD)

Unlike other constructors copy constructor is passed with another object which copies the data available from the passed object to the newly created object.

Reference:https://www.geeksforgeeks.org/constructors-in-java/

Constructor overloading in Java:

In Java, we can overload constructors like methods. The constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task.

Here, we need to understand the purpose of constructor overloading. Sometimes, we need to use multiple constructors to initialize the different values of the class.

We must also notice that the java compiler invokes a default constructor when we do not use any constructor in the class. However, the default constructor is not invoked if we have used any constructor in the class, whether it is default or parameterized. In this case, the java compiler throws an exception saying the constructor is undefined.

this keyword in java

In Java, ‘this’ is a reference variable that refers to the current object, or can be said “this” in Java is a keyword that refers to the current object instance. It can be used to call current class methods and fields, to pass an instance of the current class as a parameter, and to differentiate between the local and instance variables. Using “this” reference can improve code readability and reduce naming conflicts.

Methods to use ‘this’ in Java(TBD)

Following are the ways to use the ‘this’ keyword in Java mentioned below:

1.Using the ‘this’ keyword to refer to current class instance variables.
2.Using this() to invoke the current class constructor
3.Using ‘this’ keyword to return the current class instance
4.Using ‘this’ keyword as the method parameter
5.Using ‘this’ keyword to invoke the current class method
6.Using ‘this’ keyword as an argument in the constructor call

Use of this () in constructor overloading:

However, we can use this keyword inside the constructor, which can be used to invoke the other constructor of the same class.

Example

    public class Student {  
    //instance variables of the class  
    int id,passoutYear;  
    String name,contactNo,collegeName;  

    Student(String contactNo, String collegeName, int passoutYear){  
    this.contactNo = contactNo;  
    this.collegeName = collegeName;  
    this.passoutYear = passoutYear;  
    }  

    Student(int id, String name){  
    this("9899234455", "IIT Kanpur", 2018);  
    this.id = id;  
    this.name = name;  
    }  

    public static void main(String[] args) {  
    //object creation  
    Student s = new Student(101, "John");  
    System.out.println("Printing Student Information: \n");  
    System.out.println("Name: "+s.name+"\nId: "+s.id+"\nContact No.: "+s.contactNo+"\nCollege Name: "+s.contactNo+"\nPassing Year: "+s.passoutYear);  
    }  
    }  
Enter fullscreen mode Exit fullscreen mode

Reference:https://www.javatpoint.com/constructor-overloading-in-java

Program:

public class SuperMarket
{
//class specific
static String name = "SB SuperMarket"; 
static int doorNo = 10; 
static boolean open = true; 
//non-static ---> Instance specific
String product_name; 
int price, discount; 

SuperMarket(String product_name, int price, int discount)
{
this.product_name = product_name; 
this.price = price; 
this.discount = discount; 
}

public static void main(String[] args)
{
SuperMarket product1 = new SuperMarket("cinthol", 22,2); 
SuperMarket product2 = new SuperMarket("biscuits",30,5);
SuperMarket product3 = new SuperMarket("cake",10,1); 
product1.sell();
product2.sell(); 
product3.sell();
product2.return_product(); 

}
public void return_product()
{
System.out.println("returning "+product_name);
}
public void sell()
{
System.out.println(product_name); 
System.out.println(price);
System.out.println(discount);
}
}

Enter fullscreen mode Exit fullscreen mode

Output:

neelakandan@neelakandan-HP-Laptop-15s-eq2xxx:~/Documents/B14$ java SuperMarket 
cinthol
22
2
biscuits
30
5
cake
10
1
returning biscuits
neelakandan@neelakandan-HP-Laptop-15s-eq2xxx:~/Documents/B14$ ^C

Enter fullscreen mode Exit fullscreen mode
fullstack Article's
30 articles in total
Favicon
Getting Started with MERN Stack: A Beginner's Guide
Favicon
Understanding Microservices Architecture in Full-Stack Applications
Favicon
Looking for Middle Frontend Platform/Fullstack Engineer
Favicon
Bootcamp vs. Self-Taught: Which path is the best?
Favicon
System.out.println()
Favicon
Angular Signals and Their Benefits
Favicon
Converting date by user time zone in "NestJS", and entering and displaying date in "Angular"
Favicon
AI and the Full Stack Developer in 2025
Favicon
Should I look for a new job?
Favicon
System.out.println()
Favicon
Constructor
Favicon
lowCalAlt_update 6
Favicon
7 Practical Ways to Build Backends Much Faster as a Developer
Favicon
Dumriya Live - AWS Oriented Full Stack Application Infrastructure Overview
Favicon
Hello,help review my fullstack website stack : nestjs,mongodb and reactjs. https://events-org-siiv.vercel.app/
Favicon
Full stack development
Favicon
Title: "My Journey as an Aspiring Full-Stack Developer" Introduction: Hello, dev.to community! My name is Shoeb Ahmad, and I'm an aspiring full-stack developer. My journey into web development began with a passion for creating dynamic and responsive web
Favicon
Java Constructors
Favicon
Best Leading Software Development Company In Lucknow
Favicon
What is Microfrontend, and How to Implement It?
Favicon
Building REST APIs vs GraphQL: Which One is Right for Your Project?
Favicon
https://dev.to/hanzla-baig/full-stack-developers-roadmap-dch
Favicon
Full-Stack Next.js 15 Development Using Zod, Typescript, tRPC, react-query, and Sequelize ORM
Favicon
Complete Full-Stack Web App Development Roadmap
Favicon
🚀 Developers, Are You Betting on the Right Framework? 🚀
Favicon
Want to be a better full-stack developer? Know the web and HTTP principles
Favicon
DTO & DAO in Software Development
Favicon
Advanced JavaScript concepts that every Javascript devloper should know!
Favicon
Mastering Full Stack Development: Your Gateway to a Dynamic Career
Favicon
Navigating the Web Development Landscape: Finding Your Role

Featured ones: