Lesson Overview
This lesson explains classes, objects, instance variables, instance methods, object declaration, object creation, and the difference between instance and class members.
What Is a Class?
A class is a blueprint for creating objects. It describes what data an object can store and what actions it can perform.
For example, a Phone class might describe data such as brand, model, and screen size, and behavior such as power on, call, and send message.
What Is an Object?
An object is a specific instance of a class. If Phone is the class, then a specific phone model owned by a person can be represented as an object.
Objects usually have:
- state: values stored in variables
- behavior: actions implemented as methods
Software objects are modeled after real-world objects by combining data and behavior.
Creating a Class
A class header includes an optional access modifier, the keyword class, and the class name.
public class Student {
// fields and methods go here
}
Fields are variables that belong to the class or object.
public class Student {
int age = 18;
}
Access Modifiers and Information Hiding
Fields are often marked private so other classes cannot change them directly. This protects object data and encourages controlled access through methods.
Common modifiers:
| Modifier | Meaning |
|---|---|
public | Accessible from other classes |
private | Accessible only inside the same class |
protected | Accessible in the same package or subclasses |
| no modifier | Package-level access |
static | Belongs to the class rather than one object |
final | Cannot be changed after assignment |
Instance Methods
Instance methods belong to objects. They are usually called after creating an object with new.
Setter methods store values. Getter methods return values.
Activity: Student Class with Instance Methods
Declaring and Creating Objects
Declaring a variable of a class type does not create an object yet.
Student learner; // declaration only
learner = new Student(); // object creation
Both steps can be combined.
Student learner = new Student();
The new operator reserves memory and calls a constructor.
Activity: Class with Multiple Fields
Instance Members and Static Members
An instance variable belongs to one object. Each object gets its own copy.
A static variable belongs to the class. All objects share the same static variable.
public class SchoolRecord {
static int schoolCode = 100;
int studentNumber;
}
If one object changes a static variable, all objects see the updated value.
Activity: Static Variable Demonstration
Laboratory Exercises
Try It: Classes and Objects
Create a second Student object with different values and call displayInfo() on it.