Understanding Classes and Objects in Java
Course: Core Java Training
Topic: Understanding Classes and Objects
Course Link: Core Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Classes and Objects in Java
Java is an object-oriented programming language that uses classes and objects to organize programs around data and behavior. A class defines the structure and capabilities of a type, while an object is an individual instance of that class.
For example, a Car class can describe properties such as brand, color, and speed, along with behaviors such as starting, accelerating, and braking. Individual car objects can have different brands, colors, and speeds while sharing the same class structure.
Classes and objects help developers represent real-world concepts, organize related information, reuse code, and build applications that are easier to maintain.
Learning Objectives
- Understand the meaning and purpose of classes and objects.
- Learn how to declare a class and define its members.
- Create objects using the
new keyword.
- Understand fields, methods, and constructors.
- Access object data and call instance methods.
- Understand instance variables, local variables, and static members.
- Explore object references, multiple objects, and the
this keyword.
- Apply encapsulation to protect object data.
- Practice creating Java programs using classes and objects.
2. What Is a Class in Java?
A class is a blueprint or template that defines the data and behavior associated with a particular type of object. It can contain fields, constructors, methods, initialization blocks, and nested types.
For example, a Student class can define a student's name, roll number, and marks. It can also provide methods to display student information or calculate a result.
Basic Syntax of a Class
class ClassName {
// Fields or variables
// Constructors
// Methods
}
Example: Creating a Simple Class
class Student {
String name;
int age;
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
In this example, Student is a class. It declares two fields, name and age, and an instance method named displayDetails().
Declaring a class does not automatically create a student object. An object must be instantiated before instance members can be used through an object reference.
3. What Is an Object in Java?
An object is an instance of a class. It represents a particular entity with state and behavior.
An object typically has three conceptual characteristics:
- State: The information stored in the object's fields, such as a student's name or age.
- Behavior: The operations the object can perform through its methods.
- Identity: The object's distinct identity, which allows it to be distinguished from other objects even if their field values are the same.
Example: Creating and Using an Object
class Student {
String name;
int age;
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class StudentDemo {
public static void main(String[] args) {
Student student = new Student();
student.name = "Aarav";
student.age = 20;
student.displayDetails();
}
}
Output
Name: Aarav
Age: 20
The statement new Student() creates a new Student object. The reference variable student refers to that object. The dot operator is used to access its fields and call its instance method.
4. Difference Between a Class and an Object
| Basis |
Class |
Object |
| Meaning |
A blueprint that defines a type. |
An instance of a class. |
| Purpose |
Defines common fields and behavior. |
Represents an individual entity with its own state. |
| Declaration |
Declared using a class declaration. |
Usually created using new for a class. |
| Memory and lifetime |
Defines the type; it is not itself an ordinary instance of that class. |
An object has runtime state and exists while reachable or otherwise retained by the runtime. |
| Example |
class Car { } |
Car car = new Car(); |
| Number |
A class can define a type for many objects. |
Many distinct objects can be created from the same class. |
5. Fields and Instance Variables
Fields are variables declared inside a class but outside its methods and constructors. Instance fields belong to individual objects, so each object normally has its own copy of each instance field.
For example, two Student objects can have different names and marks even though both objects were created from the same class.
Example: Instance Fields
class Employee {
String name;
double salary;
}
public class EmployeeDemo {
public static void main(String[] args) {
Employee employee1 = new Employee();
employee1.name = "Neha";
employee1.salary = 45000;
Employee employee2 = new Employee();
employee2.name = "Rahul";
employee2.salary = 52000;
System.out.println(employee1.name + ": " + employee1.salary);
System.out.println(employee2.name + ": " + employee2.salary);
}
}
Output
Neha: 45000.0
Rahul: 52000.0
The two objects have separate instance-field values. Changing the name or salary of one object does not automatically change the corresponding field of the other object.
6. Methods in a Class
A method defines an operation that an object or class can perform. Instance methods can access instance fields directly and are generally called through an object. Static methods belong to the class and are commonly used for operations that do not require a particular object's state.
Basic Method Syntax
returnType methodName(parameters) {
// Method body
return value;
}
If a method does not return a value, its return type is void.
Example: Methods in a Class
class Rectangle {
double length;
double width;
double calculateArea() {
return length * width;
}
double calculatePerimeter() {
return 2 * (length + width);
}
}
public class RectangleDemo {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
rectangle.length = 10;
rectangle.width = 5;
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());
}
}
Output
Area: 50.0
Perimeter: 30.0
The Rectangle class groups rectangle dimensions and the calculations related to them. Its methods reuse the object's field values to calculate the area and perimeter.
7. Constructors in Java
A constructor is a special class member used to initialize a newly created object. Its name must match the class name, and it has no return type—not even void.
When an object is created with new, Java allocates and initializes the object, then invokes the selected constructor. Constructors can accept parameters so that objects begin with specific values.
Types of Constructor Patterns
- Default constructor: If a class declares no constructors, Java provides a no-argument default constructor.
- No-argument constructor: A constructor explicitly declared without parameters.
- Parameterized constructor: A constructor that accepts parameters to initialize an object.
Java does not automatically provide a default constructor if the class declares another constructor.
Example: Parameterized Constructor
class Student {
String name;
int age;
Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class ConstructorDemo {
public static void main(String[] args) {
Student student = new Student("Priya", 21);
student.display();
}
}
Output
Name: Priya
Age: 21
The constructor receives the values "Priya" and 21 and uses them to initialize the new object.
8. Using the this Keyword
The this keyword refers to the current object in an instance context. It is frequently used to distinguish instance fields from constructor or method parameters with the same names.
Example
class Employee {
String name;
double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
void display() {
System.out.println(name + " earns " + salary);
}
}
public class ThisDemo {
public static void main(String[] args) {
Employee employee = new Employee("Amit", 60000);
employee.display();
}
}
Output
Amit earns 60000.0
In this.name = name, the left-hand side refers to the current object's field, while the right-hand side refers to the constructor parameter.
The this reference cannot be used in a static method because a static method is not associated with a particular object.
9. Creating Multiple Objects from One Class
A single class can be used to create many objects. Each object has its own identity and, for instance fields, its own state.
Example: Multiple Book Objects
class Book {
String title;
double price;
Book(String title, double price) {
this.title = title;
this.price = price;
}
void displayBook() {
System.out.println(title + " - Rs. " + price);
}
}
public class BookDemo {
public static void main(String[] args) {
Book book1 = new Book("Core Java", 450);
Book book2 = new Book("OOP Concepts", 350);
Book book3 = new Book("Java Practice", 500);
book1.displayBook();
book2.displayBook();
book3.displayBook();
}
}
Output
Core Java - Rs. 450.0
OOP Concepts - Rs. 350.0
Java Practice - Rs. 500.0
All three objects use the same class definition but contain different title and price values. This is one of the main benefits of object-oriented design.
10. Reference Variables and Object References
A reference variable stores a reference to an object rather than containing the complete object itself. A reference can be used to access an object's members when it refers to a valid object.
Example
class Car {
String brand;
}
public class ReferenceDemo {
public static void main(String[] args) {
Car car1 = new Car();
car1.brand = "Toyota";
Car car2 = car1;
car2.brand = "Honda";
System.out.println(car1.brand);
System.out.println(car2.brand);
}
}
Output
Honda
Honda
The statement Car car2 = car1; copies the reference, not the object. Both variables refer to the same object, so changing its brand through car2 is visible when reading it through car1.
To create a separate object, use another object-creation expression such as Car car2 = new Car();.
11. Default Values of Instance Fields
Java automatically assigns default values to instance fields and static fields when an object or class is initialized. Local variables declared inside methods do not receive automatic default values and must be definitely assigned before use.
| Data Type |
Default Value for Fields |
byte, short, int, long |
0 |
float, double |
0.0 or the corresponding zero value |
char |
'\u0000' |
boolean |
false |
| Reference types |
null |
Example
class Example {
int number;
boolean active;
String message;
void display() {
System.out.println(number);
System.out.println(active);
System.out.println(message);
}
}
public class DefaultValueDemo {
public static void main(String[] args) {
Example example = new Example();
example.display();
}
}
Output
0
false
null
These values are provided for fields. A local variable such as int count; inside a method must be assigned before it is read.
12. Instance Members and Static Members
Java classes can contain instance members and static members. Instance members belong to individual objects, whereas static members belong to the class.
| Feature |
Instance Member |
Static Member |
| Association |
Belongs to an object. |
Belongs to the class. |
| Storage concept |
Each object has its own instance-field state. |
One class-level field is shared by instances of that class. |
| Access |
Usually accessed through an object reference. |
Usually accessed through the class name. |
| Example |
student.name |
Student.schoolName |
Example: Static Field
class Student {
String name;
static String schoolName = "Green Valley School";
Student(String name) {
this.name = name;
}
void display() {
System.out.println(name + " - " + schoolName);
}
}
public class StaticFieldDemo {
public static void main(String[] args) {
Student student1 = new Student("Asha");
Student student2 = new Student("Rahul");
student1.display();
student2.display();
System.out.println(Student.schoolName);
}
}
Output
Asha - Green Valley School
Rahul - Green Valley School
Green Valley School
The schoolName field is shared at the class level. The name field belongs separately to each student object.
13. Encapsulation and Data Hiding
Encapsulation combines data and related methods within a class while controlling access to the object's internal state. A common practice is to declare fields private and provide methods that validate or control updates.
Example: Bank Account
class BankAccount {
private double balance;
BankAccount(double initialBalance) {
if (initialBalance < 0) {
throw new IllegalArgumentException(
"Initial balance cannot be negative."
);
}
balance = initialBalance;
}
void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException(
"Deposit must be positive."
);
}
balance += amount;
}
double getBalance() {
return balance;
}
}
public class BankDemo {
public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
account.deposit(500);
System.out.println("Balance: " + account.getBalance());
}
}
Output
Balance: 1500.0
The balance cannot be changed directly from outside the class because it is private. The deposit() method enforces a simple rule before updating it.
14. Accessing Object Members with the Dot Operator
The dot operator (.) is used to access accessible members through an object reference or class name. Instance fields and methods are commonly accessed through an object reference.
Example
class Laptop {
String brand;
void showBrand() {
System.out.println("Brand: " + brand);
}
}
public class DotOperatorDemo {
public static void main(String[] args) {
Laptop laptop = new Laptop();
laptop.brand = "Dell";
laptop.showBrand();
}
}
Output
Brand: Dell
Here, laptop.brand accesses the field and laptop.showBrand() calls the instance method. Access is subject to the member's access modifier.
15. The Relationship Between Classes and Objects in Real Applications
Classes and objects can represent the entities and services in many types of software applications.
| Application |
Possible Class |
Example Object |
Typical Behavior |
| Education system |
Student |
A particular student |
Display student details or calculate marks. |
| Banking system |
BankAccount |
A customer's account |
Deposit funds or check a balance. |
| E-commerce |
Product |
A specific product |
Display product details or calculate a price. |
| Transportation |
Car |
A particular car |
Start, accelerate, or stop. |
| Library system |
Book |
A specific book |
Display title and author details. |
These examples illustrate how classes model common structures while objects represent individual entities used by the application.
16. Common Mistakes When Working with Classes and Objects
| Mistake |
Why It Is a Problem |
Correct Approach |
| Declaring a class but never creating an object |
Instance members cannot be used without an object reference. |
Create an object when instance behavior is needed. |
| Calling an instance method directly from a static context |
No particular object is available for the call. |
Call it through an object or redesign the method if it is genuinely class-level behavior. |
| Confusing a reference with an object |
Assigning one reference to another does not create a new object. |
Use new to create another instance when required. |
| Making all fields public |
Other classes can change internal state without validation. |
Use private fields and appropriate methods where needed. |
| Forgetting constructor initialization |
Objects may begin with unintended values. |
Initialize important fields through constructors or controlled initialization methods. |
| Using the same name without understanding scope |
Parameters may hide fields and cause assignment mistakes. |
Use this.fieldName = fieldName when appropriate. |
| Using static fields for individual data |
Values are shared instead of stored separately per object. |
Use instance fields for object-specific state. |
| Accessing a null reference |
Calling a method or accessing a field through null causes a NullPointerException. |
Ensure the reference points to an object before accessing its members. |
17. Best Practices for Designing Classes and Objects
- Give every class a meaningful name that represents its purpose.
- Keep fields private when direct external access is unnecessary.
- Use constructors to initialize objects into valid states.
- Use instance fields for data that differs from one object to another.
- Use static fields for data genuinely shared by the class.
- Keep methods focused on clear, related operations.
- Choose descriptive method and variable names.
- Validate important input values before changing object state.
- Avoid creating unnecessary objects when an existing object can be used appropriately.
- Do not assume that assigning one reference variable to another creates a copy of an object.
- Use packages to organize classes in larger projects.
- Write tests for important class behavior and edge cases.
18. Practical Project: Student Management Program
Objective: Create a small Java program that uses a class, multiple objects, a constructor, fields, and methods to manage student information.
Requirements
- Create a
Student class with private fields for name, roll number, and marks.
- Use a constructor to initialize the fields.
- Create a method that returns a grade based on the student's marks.
- Create a method to display the student's details.
- Create multiple student objects and display their information.
- Validate that marks are within the range from 0 to 100.
Sample Solution
class Student {
private final String name;
private final int rollNumber;
private final int marks;
Student(String name, int rollNumber, int marks) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException(
"Name cannot be empty."
);
}
if (rollNumber <= 0) {
throw new IllegalArgumentException(
"Roll number must be positive."
);
}
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException(
"Marks must be between 0 and 100."
);
}
this.name = name;
this.rollNumber = rollNumber;
this.marks = marks;
}
String calculateGrade() {
if (marks >= 90) {
return "A";
} else if (marks >= 75) {
return "B";
} else if (marks >= 60) {
return "C";
} else if (marks >= 40) {
return "D";
} else {
return "F";
}
}
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
System.out.println("Grade: " + calculateGrade());
System.out.println("--------------------");
}
}
public class StudentManagement {
public static void main(String[] args) {
Student student1 = new Student("Asha", 101, 92);
Student student2 = new Student("Rahul", 102, 78);
Student student3 = new Student("Neha", 103, 56);
student1.displayDetails();
student2.displayDetails();
student3.displayDetails();
}
}
Sample Output
Name: Asha
Roll Number: 101
Marks: 92
Grade: A
--------------------
Name: Rahul
Roll Number: 102
Marks: 78
Grade: B
--------------------
Name: Neha
Roll Number: 103
Marks: 56
Grade: D
--------------------
The project demonstrates how one class defines the structure and behavior of student objects. Each object stores its own values, and the same methods work with every student instance.
19. Additional Practice Exercises
- Car Class: Create a
Car class with brand, model, and year fields. Add a method to display its details.
- Bank Account: Create a
BankAccount class with a private balance and methods for deposit, withdrawal, and checking the balance.
- Book Class: Create a
Book class with title, author, and price. Create at least three book objects.
- Rectangle Class: Add length and width fields with methods to calculate area and perimeter.
- Employee Class: Create an employee object with a name and salary, and add a method to calculate a bonus.
- Static Counter: Create a class with a static field that tracks how many objects have been constructed. Consider how constructors and object creation affect the count.
- Reference Experiment: Assign one object reference to another, change a field, and observe the result. Then create a second object and compare the behavior.
20. Interview Questions and Answers
Q1. What is a class in Java?
Answer: A class is a blueprint that defines a type's fields, methods, constructors, and other members.
Q2. What is an object in Java?
Answer: An object is an instance of a class with its own identity and state, and it can use the behavior defined by the class.
Q3. What is the difference between a class and an object?
Answer: A class defines a type and its structure, while an object is a particular instance created from that type.
Q4. How do you create an object in Java?
Answer: A common way is to use the new keyword, such as Student student = new Student();, assuming an accessible no-argument constructor exists.
Q5. What is a constructor?
Answer: A constructor initializes a newly created object. Its name matches the class name, and it has no return type.
Q6. Can a class have multiple constructors?
Answer: Yes. A class can define multiple constructors with different parameter lists. This is called constructor overloading.
Q7. What is an instance variable?
Answer: An instance variable is a non-static field whose value is associated with an individual object.
Q8. What is a static variable?
Answer: A static variable is associated with the class and is shared by instances of that class rather than having a separate copy for each object.
Q9. What is the purpose of the this keyword?
Answer: The this keyword refers to the current object in an instance context. It is often used to distinguish fields from parameters with the same names.
Q10. What happens when one object reference is assigned to another?
Answer: The reference value is copied, so both variables can refer to the same object. A new object is not created by the assignment alone.
Q11. What is encapsulation?
Answer: Encapsulation combines data and behavior while controlling access to internal state, often through private fields and appropriate methods.
Q12. What are default values in Java?
Answer: Instance and static fields receive default values based on their types. Local variables must be assigned before they are read.
Q13. Can a static method access an instance variable directly?
Answer: No. A static method needs an object reference to access an instance field because it is not associated with a particular object.
Q14. What is the dot operator used for?
Answer: The dot operator accesses accessible members through an object reference or a class name, depending on the member.
Q15. Why are classes and objects important in Java?
Answer: They help model entities, group related data and behavior, promote reuse, and provide a foundation for object-oriented design.
21. Quick Revision Checklist
- A class defines a type and its members.
- An object is an instance of a class.
- Objects are commonly created with the
new keyword.
- Fields represent data, while methods define behavior.
- Constructors initialize newly created objects.
- The
this keyword refers to the current object in an instance context.
- Instance fields normally hold separate values for each object.
- Static fields are associated with the class and shared among its instances.
- Reference assignment copies a reference, not an object.
- Instance and static fields receive default values; local variables do not.
- Encapsulation helps protect internal state.
- Meaningful class names, focused methods, and input validation improve code quality.
22. Conclusion
Classes and objects are fundamental concepts in Core Java. A class defines the common structure and behavior of a type, while each object represents an individual instance with its own state. Constructors initialize objects, fields store information, and methods define the operations that objects can perform.
Understanding object references, instance and static members, the this keyword, and encapsulation will help you write Java programs that are organized, reusable, and maintainable. Practice by creating small classes for students, employees, books, bank accounts, and other familiar entities before moving on to inheritance, polymorphism, and other object-oriented programming concepts.
Continue learning through the Core Java Training Course, register through the course demo page, or visit the JustAcademy website.