In Java, classes and objects are fundamental building blocks of object-oriented programming (OOP). Classes serve as blueprints or templates for creating objects, which are instances of those classes. Objects encapsulate data (attributes) and behavior (methods), representing real-world entities.
In Java, a class is a blueprint or template for creating objects. It defines the attributes and methods that all objects of that class will have. An object is an instance of a class, and it encapsulates data (attributes) and behavior (methods).
Structure of a Class
A class definition consists of the following components:
Access Modifier: Specifies who can access the class. Possible modifiers are public, private and protected.
Class Name: Identifies the class.
Class Body: Encloses the class members, which include fields, methods,
// Class declaration
public class ClassName {
// Fields (attributes or variables)
datatype fieldName;
// Constructor
public ClassName(parameters) {
// Constructor body
}
// Methods
returnType methodName(parameters) {
// Method body
}
}
Example: Let’s start by creating a BankAccount class to represent a basic bank account.
public class BankAccount {
// Attributes
private String accountHolder;
private double balance;
// Constructor
public BankAccount(String accountHolder, double initialBalance) {
this.accountHolder = accountHolder;
this.balance = initialBalance;
}
// Methods
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposit of $" + amount + " successful. New balance: $" + balance);
} else {
System.out.println("Invalid deposit amount.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawal of $" + amount + " successful. New balance: $" + balance);
} else {
System.out.println("Invalid withdrawal amount or insufficient funds.");
}
}
public void checkBalance() {
System.out.println("Account balance for " + accountHolder + ": $" + balance);
}
}
Explanation:
Attributes: The BankAccount class has two private attributes – accountHolder to store the account holder’s name and balance to store the account balance.
Constructor: The constructor is used to initialize the object when it is created. It takes the account holder’s name and initial balance as parameters.
Methods:
deposit(double amount): Adds the specified amount to the account balance.
withdraw(double amount): Subtracts the specified amount from the account balance, if sufficient funds are available.
checkBalance(): Displays the account balance.
In Java, objects are instances of classes. They represent real-world entities and encapsulate both data (attributes) and behavior (methods). Objects interact with each other to perform tasks and achieve the program’s objectives.
1. Key Characteristics of Objects
Encapsulation: Objects encapsulate data and behavior, protecting the data from external access and ensuring that it can only be modified through authorized methods.
Identity: Each object has a unique identity that distinguishes it from other objects. This identity allows objects to be referenced and manipulated within the program.
State: Objects maintain their state through their attributes. The state of an object represents its current condition and can be modified over time.
Behavior: Objects exhibit behavior through their methods. Methods define the actions that an object can perform and encapsulate the logic for those actions.
2. Creating Objects
Objects are created using the new operator followed by the class name and constructor arguments. For example, to create an object of the BankAccount class, you would use the following code:
public class BankingSystem {
public static void main(String[] args) {
// Creating BankAccount objects
BankAccount account1 = new BankAccount("John Doe", 1000.0);
BankAccount account2 = new BankAccount("Jane Doe", 500.0);
// Accessing Object Members
account1.deposit(500.0);
account1.withdraw(200.0);
account1.checkBalance();
account2.withdraw(100.0);
account2.deposit(300.0);
account2.checkBalance();
}
}
//Output
Deposit of $500.0 successful. New balance: $1500.0
Withdrawal of $200.0 successful. New balance: $1300.0
Account balance for John Doe: $1300.0
Withdrawal of $100.0 successful. New balance: $400.0
Deposit of $300.0 successful. New balance: $700.0
Account balance for Jane Doe: $700.0
Explanation: Two BankAccount objects, account1, and account2, are created with initial balances of $1000.0 and $500.0, respectively. Transactions are performed on account1 and account2 using the deposit, withdraw, and checkBalance methods. The results of the transactions are printed on the console.
3. Accessing Object Members
Attributes and methods of an object are accessed using the dot operator (.) as shown in the above example(lines 9-15). For example, to access the name attribute of the student1 object and call the printStudentInfo() method, you would use the following code:
4. Object Relationships
Objects can interact with each other through their methods and attributes. They can establish relationships, pass messages, and exchange data. These interactions form the basis of object-oriented programming.
5. Benefits of Objects
Objects provide several benefits in Java programming:
Modular Code: Objects promote modularity by organizing code into self-contained units.
Reusability: Objects facilitate code reuse by encapsulating common functionalities.
Maintainability: Objects enhance code maintainability by isolating changes and reducing dependencies.
Extensibility: Objects support extensibility by allowing new functionalities to be added without modifying existing code.
Attributes: Attributes are variables that represent the state of an object. They are also known as fields or data members. Attributes store the data that is relevant to the object. For example, a car object might have attributes such as color, make, model, and year.
Methods: Methods are functions that define the behavior of an object. They are also known as operations. Methods encapsulate the actions that an object can perform. For example, a car object might have methods such as start, stop, accelerate, and brake.
Encapsulation: Encapsulation is the bundling of data and methods into a single unit. It is a key principle of OOP. Encapsulation helps to protect the data of an object from being accessed or modified by unauthorized code.
Abstraction: Abstraction is the process of hiding the details of an object’s implementation and only exposing its essential features. It is another key principle of OOP. Abstraction allows users to interact with objects without having to know how they are implemented.
Inheritance: Inheritance is the ability of a class to inherit the attributes and methods of another class. It is a powerful mechanism for code reuse. Inheritance allows classes to be organized into a hierarchy, with each class inheriting from its parent class.
Polymorphism: Polymorphism is the ability of objects to take on different forms. It is a powerful mechanism for flexibility. Polymorphism allows objects to respond to the same method call in different ways, depending on the type of object.
Understanding classes and objects is fundamental to mastering Java and object-oriented programming. Classes provide a blueprint for creating objects, and objects encapsulate data and behavior. With the concepts of encapsulation, inheritance, and polymorphism, you can build robust and maintainable Java applications.