Constructors
-
Special methods for object initialization
-
Characteristics:
- Same name as class
- No return type
- Can be overloaded
- Use
thiskeyword to reference current object
-
A constructor is a special method that:
- Is automatically called whenever an object is created
- Initializes object properties during object creation
- Has the same name as the class
- Does not have a return type (not even void)
- Is usually declared as public (can be private in special cases)
-
Default Constructor
- Every Java class has a default constructor provided by the compiler
- It’s automatically available if no constructor is explicitly defined
- When you define your own constructor(s), the default constructor is removed
-
Types of Constructors:
- Default
- Non-Parameterized/Parameterized
-
Why Java Creates Default Constructor:
- Object Initialization
- Ensures every object has basic initialization
- Sets default values for fields
- Allows object creation without parameters
- Default Values
- numeric types (int, double, etc.) → 0
- boolean → false
- object references → null
- When Created
- Only when no constructor is explicitly defined
- Automatically inserted by compiler
- Has no parameters and empty bodv
- Object Initialization
-
Constructor Overloading
- Multiple constructors can be defined in a class
- Must have different parameter lists (since names are always the same)
- Allows for flexible object creation
- Similar to method overloading
-
For example, see this code (
CylinderTest.java, below)CylinderTest.java// program to calculate the volume and surface area of a cylinder using non parameterized as well as parameterized constructor class Cylinder { private int radius; private int height; public Cylinder() { radius = height = 1; } public Cylinder(int r, int h) { this.radius = r; this.height = h; } public int getHeight() { return height; } public int getRadius() { return radius; } public void setHeight(int h) { if (h >= 0) height = h; else height = 0; } public void setRadius(int r) { if (r >= 0) radius = r; else radius = 0; } public void setDimensions(int h, int r) { height = h; radius = r; } public double lidArea() { return Math.PI * radius * radius; } public double perimeter() { return 2 * Math.PI * radius; } public double drumArea() { return 2 * lidArea() + perimeter() * height; } public double volume() { return lidArea() * height; } } public class CylinderTest { public static void main(String[] args) { Cylinder c = new Cylinder(); c.setHeight(10); c.setRadius(7); c.setDimensions(10, 7); System.out.println("LidArea " + c.lidArea()); System.out.println("Circumference " + c.perimeter()); System.out.println("totalSurfaceArea " + c.drumArea()); System.out.println("Volume " + c.volume()); System.out.println("Height" + c.getHeight()); System.out.println("Radius" + c.getRadius()); } }Runs in your browser with Java 21. Ctrl/⌘ + Enter to run.Built with CheerpJ