0% found this document useful (0 votes)
17 views6 pages

Constructors in Java

Uploaded by

Aman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views6 pages

Constructors in Java

Uploaded by

Aman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Constructors in Java

Definition
 A constructor in Java is a special method used to initialize objects of a class.
 It is called automatically when an object is created using the new keyword.
 Constructors have the same name as the class and no return type (not even void).
Key Characteristics
1. Purpose: Initializes instance variables and sets up the initial state of an object.
2. Name: Must match the class name exactly (case-sensitive).
3. No Return Type: Unlike regular methods, constructors do not specify a return type.
4. Automatic Invocation: Called implicitly when an object is instantiated.
5. Access Modifiers: Can have public, private, protected, or default (package-private)
access.
Types of Constructors
1. Default Constructor:
o Provided by Java if no constructor is defined in the class.
o Takes no parameters and initializes instance variables to default values (e.g., 0 for
int, null for objects).
o Example:
java
class MyClass {
MyClass() {
// Default constructor
}
}
2. Parameterized Constructor:
o Takes parameters to initialize instance variables with specific values.
o Example:
java
class Student {
String name;
int age;

Student(String name, int age) {


[Link] = name;
[Link] = age;
}
}
3. Copy Constructor:
o Initializes an object using another object of the same class.
o Example:
java
class Student {
String name;
int age;

Student(Student other) {
[Link] = [Link];
[Link] = [Link];
}
}
Constructor Overloading
 A class can have multiple constructors with different parameter lists (same name,
different signatures).
 Example:
java
class Book {
String title;
String author;
double price;

// Constructor with title and author


Book(String title, String author) {
[Link] = title;
[Link] = author;
}

// Constructor with title, author, and price


Book(String title, String author, double price) {
[Link] = title;
[Link] = author;
[Link] = price;
}
}
The this Keyword
 Used to differentiate instance variables from constructor parameters with the same name.
 Example:
java
class Car {
String model;
int year;
Car(String model, int year) {
[Link] = model; // [Link] refers to instance variable
[Link] = year;
}
}
 Can also be used to call another constructor in the same class (constructor chaining) using
this().
o Must be the first statement in the constructor.
o Example:
java
class Employee {
String name;
int id;

Employee(String name) {
this(name, 0); // Calls parameterized constructor
}

Employee(String name, int id) {


[Link] = name;
[Link] = id;
}
}
The super Keyword
 Used to call a constructor in the parent class.
 Must be the first statement in the constructor.
 Example:
java
class Animal {
String species;

Animal(String species) {
[Link] = species;
}
}

class Dog extends Animal {


String breed;

Dog(String species, String breed) {


super(species); // Calls parent class constructor
[Link] = breed;
}
}
Important Notes
1. No Explicit Return: Constructors cannot return values, as their purpose is to initialize
objects.
2. No Inheritance: Constructors are not inherited by subclasses, but the parent class’s
constructor can be called using super().
3. Private Constructors:
o Used to prevent instantiation (e.g., in singleton classes or utility classes).
o Example (Singleton pattern):
java
class Singleton {
private static Singleton instance = new Singleton();

private Singleton() {
// Private constructor
}

public static Singleton getInstance() {


return instance;
}
}
4. Default Values:
o If no constructor is defined, Java provides a default constructor.
o If a parameterized constructor is defined, the default constructor is not provided
unless explicitly defined.
5. Static Initialization vs. Constructor:
o Constructors initialize instance variables for objects.
o Static blocks or fields initialize class-level (static) variables, not tied to object
creation.
6. Exception Handling:
o Constructors can throw exceptions, which must be handled by the caller.
o Example:
java
class MyClass {
MyClass(int value) throws IllegalArgumentException {
if (value < 0) {
throw new IllegalArgumentException("Value cannot be negative");
}
}
}
Common Use Cases
 Initializing object state (e.g., setting default or provided values).
 Enforcing mandatory attributes (using parameterized constructors).
 Implementing design patterns like Singleton.
 Setting up resources (e.g., database connections, file handles) during object creation.
Example Program
java
class Person {
String name;
int age;

// Default constructor
Person() {
name = "Unknown";
age = 0;
}

// Parameterized constructor
Person(String name, int age) {
[Link] = name;
[Link] = age;
}

// Copy constructor
Person(Person other) {
[Link] = [Link];
[Link] = [Link];
}

void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}

public class Main {


public static void main(String[] args) {
Person p1 = new Person(); // Default constructor
Person p2 = new Person("Alice", 25); // Parameterized constructor
Person p3 = new Person(p2); // Copy constructor

[Link](); // Name: Unknown, Age: 0


[Link](); // Name: Alice, Age: 25
[Link](); // Name: Alice, Age: 25
}
}
Key Points to Remember
 Constructors are not methods but special blocks for object initialization.
 They cannot be static, final, or abstract.
 Overloading allows flexibility in object creation.
 Use this() for constructor chaining and super() for parent class constructor calls.
 Private constructors restrict instantiation, useful in specific design patterns.

You might also like