Java — Classes and Objects
Basics of Java —Part III
Definition of Class
Consider the following example:
package e_classes_objects;
class Date {
private int day;
private int month;
private int year;
...
}This code defines a Java class named Date which is, by default, public (Java allows public to be omitted). Within this class, three private integer variables are declared: day, month, and year. These variables are private, which means they can only be accessed and modified within the Date class itself and not from outside of it. This encapsulation helps in ensuring data integrity and preventing unwanted external access to these variables.
What are the Instance Variables?
Instance variables, also known as member variables or attributes, are variables declared within a class but outside of any method, constructor, or block. These variables hold data that is unique to each instance (or object) of the class.
In object-oriented programming languages like Java, each object created from a class has its own copy of instance variables, distinct from other objects created from the same class. Instance variables define the state of an object and can have different values for different instances of the class.
In the provided Date class, day, month, and year are instance variables. Each Date object created from this class will have its own set of these variables, allowing each object to represent a specific date with its own day, month, and year values.
What is package?
In Java, a package is a way of organizing related classes and interfaces. It provides a namespace for the classes contained within it, helping to avoid naming conflicts between classes with the same name in different packages.
Packages also allow for better organization and management of code. They enable developers to group related classes together, making it easier to locate and maintain them. Additionally, packages facilitate access control, as classes within the same package have access to each other’s members without needing to explicitly declare them as public.
In the provided code, package e_classes_objects; specifies that the classes in this file belong to the e_classes_objects package.
Constructor
Consider the following example:
// initialize object while creating through constructor (has name of class)
public Date(int d, int m, int y) {
this.day = d;
this.month = m;
this.year = y;This code defines a constructor for the Date class.
Constructors are special methods in Java that are called when an object of a class is created using the new keyword.
Date d;
d = new Date(...); // Constructor is called The constructor we provided takes three integer parameters: d, m, and y, which represent the day, month, and year respectively. Within the constructor body, these parameters are used to initialize the instance variables day, month, and year of the Date object being created.
The this keyword is used to refer to the current object instance. In this context, this.day, this.month, and this.year refer to the instance variables of the Date object being initialized by the constructor, while d, m, and y refer to the parameters passed to the constructor.
So, when you create a new Date object and pass values for d, m, and y to the constructor, those values are assigned to the corresponding instance variables of the object, effectively initializing it to represent the specified date.
Constructor Overloading
//overloading
public Date(int d, int m) {
this.day = d;
this.month = m;
this.year = 2024;
}Overloading occurs when multiple methods in the same class have the same name but different parameter lists. When you overload a method, you essentially provide multiple versions of the same method, each accepting different parameters or parameter types.
In the context of the above mentioned code:
- The
Dateclass has two constructors: one that takes three parameters(int d, int m, int y)and another that takes two parameters(int d, int m). - Both constructors have the same name,
Date, but they differ in the number and type of parameters they accept.
With this constructor overloading, we can create Date objects using different combinations of parameters, depending on how you want to initialize them. For example:
Date date1 = new Date(21, 12, 2012);This uses the first constructor and sets the day, month, and year.Date date2 = new Date(23, 11);This uses the second constructor and sets only the day and month, while the year defaults to2024.
Overloading allows for more flexible object creation and initialization within the same class. Each constructor can offer a different way to initialize the object, depending on the requirements of the programmer or the application.
Constructor Chaining
Constructor chaining, also known as constructor invocation or constructor forwarding, is a technique in object-oriented programming where one constructor calls another constructor within the same class. This allows for code reuse and helps in avoiding redundancy when initializing objects.
In Java, constructor chaining is achieved using the this() keyword followed by the appropriate argument list to invoke another constructor of the same class. The called constructor may perform some additional initialization before or after delegating to another constructor.
Here are the key points about constructor chaining:
- Invocation Order: When one constructor calls another within the same class, the called constructor is executed before the calling constructor. This ensures that all initialization tasks defined in the called constructor are performed before the additional tasks in the calling constructor.
- Usage of
this(): Thethis()keyword is used to invoke another constructor. It can only be used in the first line of a constructor and must precede any other statements. - Overloaded Constructors: Constructor chaining is commonly used when a class has multiple constructors, allowing them to call each other based on the provided arguments. This promotes code reuse and simplifies object initialization.
- Avoiding Redundancy: Constructor chaining helps in avoiding redundancy by centralizing initialization logic in one or a few constructors, which are then called by other constructors as needed.
Example:
public Date(int d, int m) {
this(d, m, 2024);
}This line of code is calling another constructor from within the Date class constructor. It's utilizing a feature : constructor chaining or constructor invocation.
Get Binayak Basu’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s break it down:
this(d, m, 2024);: This is calling another constructor of theDateclass that accepts three parameters(int d, int m, int y), passingd,m, and2024as arguments.this: In Java,thisrefers to the current object instance.(d, m, 2024): These are the arguments passed to the constructor being called.
So, when a Date object is created using the constructor public Date(int d, int m), it will internally call the constructor public Date(int d, int m, int y) to initialize the day, month, and year values. This approach reduces code duplication and promotes code reuse within the class.
Copy Constructor
// copy constructor
public Date(Date D) {
this.day = D.day;
this.month = D.month;
this.year = D.year;
// we are accessing the private variables day, month, year from another object
// of the same type.
}The code defines a copy constructor for the Date class.
A copy constructor is a special type of constructor that creates a new object by copying the state of an existing object of the same class.
Here’s a breakdown of the copy constructor:
public Date(Date D): This declares a constructor that takes aDateobjectDas a parameter. This constructor will create a newDateobject by copying the state of theDobject.this.day = D.day;,this.month = D.month;,this.year = D.year;: Within the copy constructor, the values of theday,month, andyearinstance variables of the current object (referenced bythis) are set to the corresponding values of theDobject passed as a parameter.
The comment in the copy constructor provides additional insight into the purpose and functionality of the constructor. Let’s break it down further:
// we are accessing the private variables day, month, year from another object
// of the same type.This comment explains two key points:
- Accessing Private Variables: Private variables (
day,month, andyear) are declared within theDateclass. As they are private, they cannot be accessed directly from outside the class. However, within the same class (Date), private variables can be accessed freely, including in constructors. - Accessing Variables from Another Object: The comment clarifies that the copy constructor is accessing and copying the values of private variables (
day,month, andyear) from another object (D) of the same type (Date). This emphasizes that even though the variables are private, they can still be accessed and utilized within the class, including in constructors.
Accessors and Modifiers
Accessors (Getters): Accessors are methods that retrieve the values of private instance variables. They typically have no parameters and return the value of the variable they are accessing.
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}These methods (getDay(), getMonth(), and getYear()) return the values of the day, month, and year instance variables respectively.
Modifiers (Setters): Modifiers are methods that modify the values of private instance variables. They typically take a parameter representing the new value and assign it to the corresponding instance variable.
public void setDay(int day) {
this.day = day;
}
public void setMonth(int month) {
this.month = month;
}
public void setYear(int year) {
this.year = year;
}These methods (setDay(int day), setMonth(int month), and setYear(int year)) take an integer parameter representing the new value for the day, month, and year instance variables respectively. They then assign these values to the corresponding instance variables using the this keyword to differentiate between the instance variables and the parameters with the same name.
Accessors and modifiers provide a standardized way to interact with private instance variables, promoting encapsulation and maintaining control over how data is accessed and modified within a class.
Having said all these, what do you think will be the output of the following program:
package e_classes_objects;
class Date {
private int day;
private int month;
private int year;
// initialize object while creatin through constructor (has name of class)
public Date(int d, int m, int y) {
this.day = d;
this.month = m;
this.year = y;
}
// Constructor overloading
public Date(int d) {
this.day = d;
this.month = 12;
this.year = 2024;
}
// Constructor chaining
public Date(int d, int m) {
this(d, m, 2024);
}
// copy constructor
public Date(Date D) {
this.day = D.day;
this.month = D.month;
this.year = D.year;
// we are accessing the private variables day, month, year from another object
// of the same type.
}
// Accessors
public int getDay() {
return (day);
}
public int getMonth() {
return (month);
}
public int getYear() {
return (year);
}
// Modifiers
public void setDay(int day) {
this.day = day;
}
public void setMonth(int month) {
this.month = month;
}
public void setYear(int year) {
this.year = year;
}
// Function to format the date
public String formatDate() {
return day + "/" + month + "/" + year;
}
}
public class ClassesObjects {
public static void main(String[] args) {
Date date = new Date(21, 12, 2012);
System.out.println("Today's date is: " + date.formatDate());
// Changing the year using setter method
date.setYear(2025);
System.out.println("Updated date is: " + date.formatDate());
// use another constructor
date = new Date(23, 11);
System.out.println("Date with second constructor is: " + date.formatDate());
// use copy constructor
date = new Date(date);
System.out.println("Date with copy constructor is: " + date.formatDate());
}
}Let’s go through the main method step by step:
Date date = new Date(21, 12, 2012);: This line creates a newDateobject nameddatewith the date December 21, 2012.System.out.println("Today's date is: " + date.formatDate());: This line prints"Today's date is: "followed by the formatted date of thedateobject using theformatDate()method. So, it will print"Today's date is: 21/12/2012".date.setYear(2025);: This line changes the year of thedateobject to 2025 using thesetYearmethod.System.out.println("Updated date is: " + date.formatDate());: This line prints "Updated date is: " followed by the updated formatted date of thedateobject. Since the year was changed to 2025, it will print"Updated date is: 21/12/2025".date = new Date(23, 11);: This line creates a newDateobject nameddateusing the second constructor which only takes day and month as parameters. The year will default to 2024.System.out.println("Date with second constructor is: " + date.formatDate());: This line prints "Date with second constructor is: " followed by the formatted date of thedateobject created using the second constructor. Since the year defaults to 2024, it will print"Date with second constructor is: 23/11/2024".date = new Date(date);: This line creates a newDateobject nameddateusing the copy constructor, passing the existingdateobject as an argument.System.out.println("Date with copy constructor is: " + date.formatDate());: This line prints "Date with copy constructor is:" followed by the formatted date of thedateobject created using the copy constructor. Since it's a copy of the originaldateobject, it will have the same date, which is"23/11/2024".
So, the overall output of the program will be:
Today's date is: 21/12/2012
Updated date is: 21/12/2025
Date with second constructor is: 23/11/2024
Date with copy constructor is: 23/11/2024That’s it!
To wrap it up, we’ve unlocked the secrets of Java classes and objects. You’ve learned how to define classes, declare instance variables, and unleash the power of constructors like a boss. With constructor overloading, chaining, and even copy constructors, you’ve got all the tools to craft your Java masterpieces.
B…Y…E…😊
TIP: Click on the smiley to go to the next article! It may not work now, but will definitely work once I publish the next one🖐









