- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java Constructors
In Java, a constructor is a special block of code that is automatically called when you create a new instance of a class. Think of a constructor as the "setup" phase of an object's lifecycle. Its primary job is to prepare the new object for use, often by assigning initial values to its variables or performing necessary startup routine.
Definition:
- A constructor must have the exact same name as the class it belongs to.
- It does not have a return type—not even
void. If you add a return type, Java will treat it as a regular method, not a constructor. - It is invoked using the
newkeyword.
public class MyClass {
// Constructor
public MyClass() {
System.out.println("Object is being created!");
// Initialization logic goes here
}
}
public void MyClass() is technically a valid method name, but it is not a constructor. Java will ignore it during object creation, and your variables might remain uninitialized.
Default Constructor:
- If you do not write any constructor in your class, the Java compiler automatically inserts a "hidden" default constructor for you.
- This automatic constructor has no arguments and is often called the "no-arg" constructor.
- It initializes object members to their default values:
0for numbers,nullfor objects, andfalsefor booleans.
public class MyClass {
int count;
// If we leave this blank, Java provides:
// public MyClass() { count = 0; }
}
Parameterized Constructor:
- In real-world applications, you rarely want an object to start with empty or default data. Parameterized constructors allow you to pass specific data into an object at the moment of creation.
- This ensures that an object is "valid" from the second it exists. For example, a
Userobject should probably never exist without a username.
public class Person {
String name;
int age;
// Parameterized constructor
public Person(String name, int age) {
// We use "this" to distinguish between the class variable and the parameter
this.name = name;
this.age = age;
}
}
// Usage:
// Person p1 = new Person("Alice", 30);
this keyword inside your constructor. It clarifies that you are assigning the parameter value to the instance variable, making your code much easier to read for other developers.
Constructor Overloading:
- Just like method overloading, Java allows you to have multiple constructors in the same class, as long as they have different parameter lists (different types or different numbers of arguments).
- This provides flexibility. You might want to create a
Studentobject with just a name, or with a name and a pre-assigned ID number.
public class Student {
String name;
int rollNumber;
// Default-style constructor (no arguments)
public Student() {
this.name = "Unknown";
this.rollNumber = 0;
}
// Parameterized constructor (one argument)
public Student(String name) {
this.name = name;
this.rollNumber = 0; // Default ID
}
// Fully parameterized constructor (two arguments)
public Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
}
}
Summary
Constructors are the gateway to object-oriented programming in Java. They guarantee that your objects start their life in a predictable state. By mastering default constructors, parameterized constructors, and overloading, you can write more robust code that prevents "NullPointerExceptions" and ensures your data is always properly initialized.