Unit 5: Writing Classes
Delving Deep into Java Constructors
Introduction to Java Constructors
Java constructors are special methods used to initialize objects. They are called when an instance of an object is created and can be used to set initial values for an object's attributes. Understanding constructors is foundational for mastering object-oriented programming in Java.
Constructors in Java
Default Constructors
When we don't define any constructor in a Java class, the compiler automatically provides a default constructor. This constructor does not have any parameters and doesn't have any code within it.
For example:
class MyClass {
int x;
// No constructor defined here
}
MyClass myObj = new MyClass(); // Default constructor will be called here
Parameterized Constructors
These constructors accept parameters and allow you to set initial values for an object's attributes.
For example:
class Rectangle {
int length;
int breadth;
// Parameterized constructor
Rectangle(int l, int b) {
length = l;
breadth = b;
}
}
Rectangle rect = new Rectangle(10, 5);
Did you know?
A Java class can have multiple constructors, each with a different parameter list. This concept is known as constructor overloading.
Constructor Overloading
Just like methods, constructors can be overloaded in Java. This means you can have more than one constructor in a class, but each constructor must have a unique parameter list.
For example:
class Circle {
double radius;
// Default constructor
Circle() {
radius = 1.0;
}
// Parameterized constructor
Circle(double r) {
radius = r;
}
}
Circle circle1 = new Circle();
Circle circle2 = new Circle(5.0);
Important Note
Always ensure that constructors are named exactly the same as the class name, and they don't have a return type, not even void.
Summary
Java constructors are pivotal in object-oriented programming, allowing for the initialization of objects. They come in two flavors: default and parameterized. Additionally, the concept of constructor overloading enables a class to have multiple constructors with different parameter lists. Mastering constructors will set a strong foundation for further exploration in Java's OOP paradigms.
References
- Java Constructors Tutorial by JavaTpoint
- Java Constructors Overloading by GeeksforGeeks
AP CSA Homework Assignment
Assignment: Exploring Java Constructors
Instructions
- Create a Java class called Book with the following attributes: title, author, and numberOfPages.
- Write a default constructor that initializes the title to "Unknown", the author to "Unknown", and numberOfPages to 0.
- Write a parameterized constructor that takes in values for all three attributes and initializes them.
- Write a main method to:
- Create a default Book object and print its details.
- Create a Book object using the parameterized constructor and print its details.
- Ensure that your code is free of errors, and test your program by running it.