1. Definition of Classes and Objects
A class is an abstract data type that describes a collection of objects sharing common properties and behaviors. An object is an instance of a class. In Java, you use the keyword new to create an instance of a class—that is, an object. Each object is a concrete implementation of the class, posssessing all the attributes and methods defined in it.
To make this easier to understand, let's use an example: Human is a class. As human beings, each of us is an instance (object) of the "Human" class. Every person is a specific implementation of the "Human" class, and everyone has the basic attributes of being human.
2. Creating Classes and Objects
2.1 Creating a Class
A class defines the structure of an object, including:
- Attributes (also known as member variables): store the state information of an object.
- Methods: define the operations or behaviors an object can perform.
- Constructors: special methods used to initialize an object when it is created. The constructor name must match the class name.
public class Person {
// Attributes (member variables)
String name;
int age;
// Method
void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Most classes are declared with the class keyword. Here, Person is a class.
2.2 Creating an Object
We use the keyword new to create an object.
public class Main {
public static void main(String[] args) {
// Create an object of the Person class
Person person1 = new Person("Alice", 30);
// Call the object's method
person1.introduce(); // Output: Hello, my name is Alice and I am 30 years old.
}
}
Here, we create a new object person1. It stores the name as "Alice" and age as 30, and it can call the introduce method to output its information.
3. Usage of this
In the class definition, you may have noticed the keyword this. So, what is its purpose?
3.1 Distinguishing Member Variables from Local Variables
public class Person {
String name; // member variable
public void setName(String name) {
this.name = name; // Use 'this' to refer to the member variable 'name'
}
public String getName() {
return this.name; // Again, 'this' can be used here, but it's not strictly necessary since 'name' appears only once
}
}
If a member variable and a local variable (e.g., a method parameter) have the same name, the compiler defaults to using the local variable. To avoid confusion, you must explicitly use this to refer to the member variable.
3.2 Calling Another Constructor of the Same Class
Constructors can be overloaded within a class.
public class Person {
String name;
int age;
String email; // additional field
// First constructor: initializes only name
Person(String name) {
this.name = name;
}
// Second constructor: calls the first constructor to initialize name, and additionally initializes age
Person(String name, int age) {
this(name); // Calls the first constructor with the 'name' parameter
this.age = age;
}
// Third constructor: calls the second constructor to initialize name and age, and additionally initializes email
Person(String name, int age, String email) {
this(name, age); // Calls the second constructor with 'name' and 'age' parameters
this.email = email;
}
// Other methods...
}
As shown above, this is followed directly by parameters. The compiler automatically finds the matching constructor. This approach allows you to reuse initialization logic among constructors with minimal code, avoiding duplication and making the class structure clearer and more maintainable.
Note: this() must be the first statement in a constructor.
3.3 Returning the Current Object Reference
By returning the current object reference, you can chain multiple method calls in a single line of code. This is often called method chaining or a fluent interface.
public class User {
private String name;
private int age;
private String email;
// Constructor
public User() {}
// setName method returns the current object reference
public User setName(String name) {
this.name = name;
return this; // Return current object reference
}
// setAge method returns the current object reference
public User setAge(int age) {
this.age = age;
return this; // Return current object reference
}
// setEmail method returns the current object reference
public User setEmail(String email) {
this.email = email;
return this; // Return current object reference
}
// Example: using method chaining to set properties of a User object
public static void main(String[] args) {
User user = new User()
.setName("John Doe")
.setAge(30)
.setEmail("john.doe@example.com");
// Now the user object has all its properties set and can be used...
}
}
The User class here has three member variables. Without chaining, you would need three separate lines to assign values. With chaining, you can call multiple methods in one line.
4. Constructors
- Name matches class name: The constructor name must be exactly the same as the class name (including case).
- No return type: Constructors do not have a return type, not even
void. If you specify a return type, it becomes a regular method, not a constructor. - Automatically called: Constructors are automatically invoked when an object is created. You cannot call a constructor directly, but you can trigger it indirectly using the
newkeyword. - Can be overloaded: A class can have multiple constructors, as long as they have different paramter lists (this is called constructor overloading).
- Initialize objects: The primary purpose of a constructor is to initialize the object's state by assigning values to member variables.
- Default constructor: If a class does not explicitly define any constructor, the compiler automatically provides a no-argument default constructor. However, once you define at least one constructor, the compiler no longer provides a default one.
- Can call
this(), but must not form a cycle: For example, callingthis()back and forth in a cycle is not allowed.
public class Person {
private String name;
public Person() {
this("Default"); // OK
}
public Person(String name) {
this(); // ERROR: forms a cycle
}
}
Cyclic calls are prohibited.
To be continued...