Java Tutorial 36 of 143
Basics
- Introduction
- Download and Install Java
- Download and Install IntelliJ IDEA, Eclipse
- Creating First Java Application in IntelliJ IDEA
- JDK vs JRE vs JVM
- Print output
- Taking Input
- Identifiers
- Keywords
- Variables
- Data Types
- Literals
- Wrapper Classes
- Operators
- Decision Making
- Loops and Jump Statements
- Project: Number Guessing Game
Methods
- Introduction
- Static Methods vs Instance Methods
- Access Modifiers
- Command Line Arguments
- Variable Arguments (Varargs)
Arrays
- Introduction
- One Dimensional Arrays
- Multidimensional Arrays
- Array Class
- Arrays Class
Strings
- Introduction
- String
- StringBuffer
- StringBuilder
- String Class Methods
- StringJoiner
- StringTokenizer
OOP & Interface
- Introduction
- Java Constructors
- Java Encapsulation
- Inheritance
- Java Polymorphism
- Java Abstraction
- Interfaces
- this Keyword
- super Keyword
- static Keyword
- final Keyword
- Access Modifiers
- Nested Classes
- Anonymous Inner Class
Collections
- Collection class
- Collection Interface
- List Interface
- ArrayList
- LinkedList
- Set Interface
- HashSet
- LinkedHashSet
- TreeSet
- Queue Interface
- PriorityQueue
- Deque
- ArrayDeque
- Map Interface in Java
- HashMap
- LinkedHashMap
- TreeMap
- Hashtable
- Iterator
- Comparable and Comparator
Exception Handling
- Introduction
- Java Exception Handling
- Java Try-Catch
- Java Finally Block
- Java throw and throws
- Java Custom Exceptions
- Java Checked vs Unchecked Exceptions
Multithreading & Concurrency
- Introduction
- Thread Class
- Runnable Interface
- Thread Life Cycle
- Thread Priority
- Synchronization
- Inter-Thread Communication
- Executor Framework
- Callable and Future
- Concurrent Collections
Java 8 Features
- Lambda Expressions
- Functional Interfaces
- Method References
- Stream API
- Optional Class
- Default and Static Methods in Interface
- Date and Time API
Advanced Java Concepts
- File Handling
- Serialization and Deserialization
- Reflection API
- Annotations
- Garbage Collection
- Memory Management
- JVM Architecture
- Class Loading
- Networking
- Regular Expressions
JDBC
- Introduction
- JDBC Driver
- JDBC Connection
- Types of Statements in JDBC
- Transactions
- ResultSet
- Metadata
- Connection Pooling
Web & Enterprise
- Servlets
- JSP
- Spring Framework
- Spring Boot
- Hibernate
- REST API Development
Practice Projects
- Project: Number Guessing Game
- Project: Banking System
- Project: Student Management System
- Project: Library Management System
- Project: Quiz Application
Quiz and Coding Practice
- Java Topic-wise Quiz
- Coding Practice Problems
- Java Basics Coding Practice Problems
- Java Exercises
Interview Questions
- Core Java Interview Questions and Answers
- Advanced Java Interview Questions and Answers
- Java Interview Questions
DSA & Competitive Programming
- Arrays and Strings
- Linked List
- Stack
- Queue
- Tree
- Graph
- Heap
- Hashing
- Sorting
- Searching
- Dynamic Programming
- Roadmap for DSA in Java
Java Constructors
Learn Java constructors, including default and parameterized constructors, constructor overloading, chaining, and how constructors initialize objects.
On this page
- What Is a Constructor in Java?
- Why Are Constructors Used?
- Constructor Syntax
- Types of Constructors in Java
- Default Constructor
- Important
- No-Argument Constructor
- Parameterized Constructor
- Using this in a Constructor
- Constructor Overloading
- Constructor Chaining
- Rule for this()
- Constructor Chaining with Inheritance
- Constructors and Inheritance
- Constructor vs Method
- Can a Constructor Be static?
- Can a Constructor Be final?
- Can a Constructor Be abstract?
- Can a Constructor Be private?
- Copy Constructor Pattern
- Constructor Execution Order
- Common Constructor Mistakes
- 1. Adding a Return Type
- 2. Assuming a Default Constructor Always Exists
- 3. Calling this() After Another Statement
- 4. Confusing Constructors with Methods
- Key Points to Remember
- Conclusion
Java Constructors
A constructor in Java is a special member of a class that is automatically called when an object is created. Constructors are mainly used to initialize the object's state.
For example:
class Student {
String name;
int age;
Student() {
name = "Gaurav";
age = 20;
}
}
When an object is created:
Student student = new Student();
the Student() constructor is automatically called.
What Is a Constructor in Java?
A constructor is a special block of code that has the same name as the class and does not have a return type, not even void.
Example:
class Car {
Car() {
System.out.println("Constructor called");
}
}
Creating an object:
Car car = new Car();
Output:
Constructor called
The constructor is executed automatically when the Car object is created.
Why Are Constructors Used?
Constructors are commonly used to:
- Initialize instance variables.
- Set default values.
- Initialize objects with specific values.
- Perform required initialization when an object is created.
- Ensure an object starts in a valid state.
For example:
class Employee {
String name;
double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
}
Now an employee can be initialized when the object is created:
Employee employee = new Employee("Rahul", 50000);
Constructor Syntax
The basic syntax is:
class ClassName {
ClassName() {
// initialization code
}
}
For example:
class Student {
Student() {
System.out.println("Student object created");
}
}
A constructor has three important characteristics:
- Its name must match the class name.
- It does not have a return type.
- It is automatically invoked when an object is created.
Types of Constructors in Java
Constructors are commonly discussed as:
- Default constructor
- No-argument constructor
- Parameterized constructor
- Copy constructor pattern
Java does not have a special built-in copy constructor feature like C++, but a constructor can be designed to copy values from another object.
Default Constructor
If you do not explicitly declare any constructor in a class, the Java compiler provides a default constructor.
Example:
class Student {
String name;
int age;
}
Conceptually, the compiler provides a no-argument constructor similar to:
Student() {
}
You can then create an object:
Student student = new Student();
The instance variables receive their normal Java default values.
For example:
int→0double→0.0boolean→false- Reference types →
null
Important
The compiler provides a default constructor only when you do not declare any constructor yourself.
For example:
class Student {
Student(String name) {
this.name = name;
}
String name;
}
In this case, Java does not automatically provide Student().
Therefore:
Student student = new Student();
will cause a compilation error.
No-Argument Constructor
A no-argument constructor is a constructor that does not accept parameters.
Example:
class Student {
String name;
Student() {
name = "Unknown";
}
}
Here, Student() is explicitly defined by the programmer.
This is different from the compiler-provided default constructor because an explicitly written no-argument constructor can contain initialization logic.
Student student = new Student();
System.out.println(student.name);
Output:
Unknown
Parameterized Constructor
A parameterized constructor accepts arguments and uses them to initialize an object.
Example:
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Create an object:
Student student = new Student("Rahul", 21);
The values passed to the constructor are assigned to the object's fields.
Using this in a Constructor
The this keyword refers to the current object.
It is commonly used when constructor parameters have the same names as instance variables.
class Employee {
String name;
double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
}
Here:
this.name
refers to the instance variable, while:
name
refers to the constructor parameter.
Without this, the assignment can become ambiguous.
Constructor Overloading
Java supports constructor overloading, which means a class can have multiple constructors with different parameter lists.
Example:
class Student {
String name;
int age;
Student() {
name = "Unknown";
age = 0;
}
Student(String name) {
this.name = name;
age = 0;
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Now different constructors can be used depending on the available information:
Student student1 = new Student();
Student student2 = new Student("Rahul");
Student student3 = new Student("Amit", 22);
Constructor overloading provides flexibility when creating objects.
Constructor Chaining
Constructor chaining means one constructor calls another constructor in the same class or parent class.
The this() keyword is used to call another constructor in the same class.
Example:
class Student {
String name;
int age;
Student() {
this("Unknown", 0);
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
When this code executes:
Student student = new Student();
the no-argument constructor calls the parameterized constructor.
Rule for this()
When used inside a constructor, this() must be the first statement.
For example:
Student() {
this("Unknown", 0);
}
is valid.
But:
Student() {
System.out.println("Creating student");
this("Unknown", 0);
}
is invalid because this() is not the first statement.
Constructor Chaining with Inheritance
The super() keyword is used to call a constructor of the parent class.
Example:
class Animal {
Animal() {
System.out.println("Animal constructor");
}
}
class Dog extends Animal {
Dog() {
super();
System.out.println("Dog constructor");
}
}
Creating an object:
Dog dog = new Dog();
Output:
Animal constructor
Dog constructor
The parent constructor executes before the child constructor.
If a child constructor does not explicitly call super(), Java implicitly attempts to insert a call to the accessible no-argument constructor of the parent class.
Constructors and Inheritance
Constructors are not inherited by subclasses.
For example:
class Animal {
Animal(String name) {
System.out.println(name);
}
}
class Dog extends Animal {
Dog() {
super("Dog");
}
}
The Dog class does not inherit the Animal(String) constructor. Instead, it explicitly invokes it using super().
Constructor vs Method
Constructors and methods are different.
| Constructor | Method |
|---|---|
| Initializes an object | Performs an operation |
| Same name as the class | Can have any valid name |
| Has no return type | Has a return type or void |
| Called automatically during object creation | Usually called explicitly |
| Cannot be inherited | Methods can be inherited |
| Cannot be overridden | Methods can be overridden |
Example:
class Car {
Car() {
System.out.println("Car created");
}
void drive() {
System.out.println("Car is driving");
}
}
Here, Car() is the constructor and drive() is a method.
Can a Constructor Be static?
No. Constructors cannot be declared static.
For example, this is invalid:
class Student {
static Student() {
}
}
Constructors belong to object creation, while static members belong to the class itself.
Can a Constructor Be final?
No. Constructors cannot be declared final.
The final keyword is used with methods, variables, and classes, but it does not apply to constructors.
Can a Constructor Be abstract?
No. Constructors cannot be abstract.
An abstract method requires implementation in a subclass, while a constructor is responsible for initializing an object of its class.
Can a Constructor Be private?
Yes. A constructor can be private.
A private constructor prevents code outside the class from directly creating objects using that constructor.
Example:
class Database {
private Database() {
}
}
This prevents:
Database db = new Database();
from outside the class.
Private constructors are commonly used in patterns such as utility classes and certain singleton implementations.
Copy Constructor Pattern
Java does not provide a special copy constructor syntax, but you can create a constructor that accepts another object of the same class.
Example:
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
Student(Student other) {
this.name = other.name;
this.age = other.age;
}
}
Usage:
Student student1 = new Student("Rahul", 21);
Student student2 = new Student(student1);
The second constructor copies values from student1.
Constructor Execution Order
When an object of a child class is created, constructors execute from the parent class toward the child class.
Example:
class Animal {
Animal() {
System.out.println("Animal");
}
}
class Dog extends Animal {
Dog() {
System.out.println("Dog");
}
}
Creating the object:
Dog dog = new Dog();
Output:
Animal
Dog
This ensures that the parent portion of the object is initialized before the child portion.
Common Constructor Mistakes
1. Adding a Return Type
This is not a constructor:
void Student() {
}
It is a method named Student.
The correct constructor is:
Student() {
}
2. Assuming a Default Constructor Always Exists
If you define any constructor yourself, Java does not automatically add a no-argument constructor.
class Student {
Student(String name) {
}
}
This does not provide:
Student()
3. Calling this() After Another Statement
This is invalid:
Student() {
System.out.println("Hello");
this("Unknown");
}
this() must be the first statement.
4. Confusing Constructors with Methods
A constructor has no return type and has the same name as its class.
class Student {
Student() {
// Constructor
}
void Student() {
// Method
}
}
These are different members.
Key Points to Remember
- A constructor initializes an object when it is created.
- A constructor has the same name as its class.
- A constructor does not have a return type.
- Constructors are called automatically when objects are created.
- Java provides a compiler-generated default constructor only when no constructor is declared.
- Constructors can be overloaded.
this()is used for constructor chaining within the same class.super()is used to invoke a parent-class constructor.- Constructors are not inherited or overridden.
- Constructors can be private.
- Constructors cannot be
static,final, orabstract. - Java does not have a dedicated copy-constructor feature, but a copy-constructor pattern can be implemented manually.
Conclusion
Constructors are an important part of Java object creation and initialization. They allow developers to ensure that objects begin with appropriate values and provide different ways to initialize objects through constructor overloading and chaining.
Understanding constructors is essential for working with classes, objects, inheritance, encapsulation, and object-oriented programming in Java.
Related
-
Inheritance
Learn Java inheritance, including single, multilevel, and hierarchical inheritance, method overriding, super, and how inheritance supports code reuse and polymorphism.
-
Java Encapsulation
Learn Java encapsulation, how to protect object data using access modifiers, getters and setters, and why encapsulation improves code security and maintainability.
-
Java Polymorphism
Learn Java polymorphism, including compile-time and runtime polymorphism, method overloading, method overriding, dynamic method dispatch, and practical examples.
-
Java Abstraction
Learn Java abstraction using abstract classes and interfaces to hide implementation details, define common behavior, and build flexible object-oriented applications.