Home Java javaTutorial Java Constructors

Java Constructors

Jan 06, 2025 am 03:47 AM

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();
    }
}
Copy after login
Copy after login

** 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:

Java Constructors
3.copy constructor

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.

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

// Driver Class
class Geeks {

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

    // main function
    public static void main(String[] args)
    {
        Geeks geek = new Geeks();
    }
}
Copy after login
Copy after login

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

Program:

    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);  
    }  
    }  
Copy after login

Output:

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);
}
}

Copy after login

The above is the detailed content of Java Constructors. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles