Default Constructor
Default Constructor
A constructor is a special method called when an object is created.
No-Argument Constructor
public class Student {
String name;
int age;
public Student() {
name = "Unknown";
age = 0;
}
}
Student student = new Student();
System.out.println(student.name); // "Unknown"
Implicit Default Constructor
public class Car {
// If no constructor defined, compiler provides:
// public Car() { }
}
Car car = new Car(); // Works!
When Default is NOT Provided
public class Person {
String name;
public Person(String name) {
this.name = name;
}
}
// Person p = new Person(); // COMPILE ERROR!
Person p = new Person("Alice"); // Must use parameterized
Constructor vs Method
public class Example {
String name;
// Constructor - no return type
public Example(String name) {
this.name = name;
}
// Method - has return type
public String getName() {
return name;
}
}
Parameterized Constructors
Parameterized Constructors
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Person p = new Person("Alice", 25);
Multiple Constructors
public class Rectangle {
int width, height;
String color;
public Rectangle() {
this(10, 10, "black");
}
public Rectangle(int width, int height) {
this(width, height, "black");
}
public Rectangle(int width, int height, String color) {
this.width = width;
this.height = height;
this.color = color;
}
}
Constructor with Validation
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
if (initialBalance < 0) {
throw new IllegalArgumentException("Balance cannot be negative");
}
this.balance = initialBalance;
}
}
Constructor Overloading
Constructor Overloading
Multiple constructors with different parameter lists.
public class Student {
String name;
int age;
String major;
public Student() {
this("Unknown", 0, "Undeclared");
}
public Student(String name) {
this(name, 0, "Undeclared");
}
public Student(String name, int age) {
this(name, age, "Undeclared");
}
public Student(String name, int age, String major) {
this.name = name;
this.age = age;
this.major = major;
}
}
Overloading Rules
public class Example {
public Example(int x) { }
public Example(double x) { } // Different type
public Example(int x, int y) { } // Different count
// INVALID:
// public Example(int y) { } // Same signature!
}
Constructor Chaining
Constructor Chaining with this()
public class Person {
String name;
int age;
String email;
public Person() {
this("Unknown", 0);
}
public Person(String name, int age) {
this(name, age, null);
}
public Person(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
}
Chaining Rules
public class Example {
public Example() {
this(10); // Must be FIRST statement
// System.out.println("Hello"); // COMPILE ERROR!
}
public Example(int x) { }
}
Copy Constructor
Copy Constructor
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Copy constructor
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
}
Person original = new Person("Alice", 25);
Person copy = new Person(original);
System.out.println(copy == original); // false
Deep vs Shallow Copy
public class Employee {
String name;
int[] skills;
public Employee deepCopy(Employee other) {
Employee copy = new Employee();
copy.name = other.name;
copy.skills = other.skills.clone(); // Deep copy!
return copy;
}
}
Practice Problems
Design a stack using only queues.
Example:
Input: push(1), push(2), pop()
Output: 2
Stack: [1, 2], pop returns 2
Optimal Solution — O(n) time, O(n) space
Use two queues, transfer on push.
class MyStack {
private Queue<Integer> q1 = new LinkedList<>();
private Queue<Integer> q2 = new LinkedList<>();
public void push(int x) {
while (!q1.isEmpty()) q2.add(q1.poll());
q1.add(x);
while (!q2.isEmpty()) q1.add(q2.poll());
}
public int pop() { return q1.poll(); }
}Edge Cases:
- Push single element
- Pop from empty
Design a queue using only stacks.
Example:
Input: push(1), push(2), pop()
Output: 1
Queue: [1, 2], pop returns 1
Optimal Solution — O(1) amortized time, O(n) space
Use two stacks, transfer on pop.
class MyQueue {
private Stack<Integer> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();
public void push(int x) { s1.push(x); }
public int pop() {
if (s2.isEmpty()) while (!s1.isEmpty()) s2.push(s1.pop());
return s2.pop();
}
}Edge Cases:
- Empty queue
- Single element
Quiz
1. What happens if no constructor is defined?
2. What is constructor overloading?
3. Where must this() be placed in a constructor?
4. What is the primary purpose of Constructors?
Flashcards
Question
What is a constructor?
Click to reveal answer
Answer
A special method called when creating an object, used to initialize the object's state.
Question
What is the difference between this() and super()?
Click to reveal answer
Answer
this() calls another constructor in the same class. super() calls a constructor in the parent class.
Question
What is a copy constructor?
Click to reveal answer
Answer
A constructor that takes an object of the same class and creates a new object with the same values.
Question
What is Constructors?
Click to reveal answer
Answer
Constructors is a key concept in Java programming.
Question
When to use Constructors?
Click to reveal answer
Answer
Use Constructors when building production systems that require reliability, scalability, and maintainability.
Revision Notes
Key Takeaways
- 1.Constructors initialize objects
- 2.this() enables constructor chaining
- 3.Copy constructors create object copies
- 4.No return type in constructors
Interview Tips
- •Always provide default constructor if needed
- •Use this() to avoid code duplication
- •Understand deep vs shallow copy
- •Know when compiler provides default constructor
Cheat Sheet
Cheat Sheet
- Constructor: Same name as class, no return type
- Default: Provided if no constructor defined
- this(): Chain constructors (must be first)
- super(): Call parent constructor
- Copy: Takes same class as parameter