Look around you. A class is a blueprint or template that describes a kind of thing. An object is one actual thing built from that blueprint.
| Class (blueprint) | Objects (instances) | Attributes (what it has) | Methods (what it does) |
|---|---|---|---|
| Car | myCar, yourCar | colour, model, speed | start(), accelerate(), brake() |
| Student | Nimal, Kamala | name, indexNo, marks | study(), getGrade() |
| BankAccount | account 101, account 102 | accountNo, balance | deposit(), withdraw() |
| Dog | Rex, Bella | name, breed, age | bark(), eat() |
One class can create many objects, and each object has its own values. The class Car is not a car you can drive; myCar is.
State, behaviour and identity
Every object has three characteristics:
- State: the current values of its attributes. myCar's state might be colour = red, model = Axio, speed = 40.
- Behaviour: what it can do, defined by its methods. myCar can
start(),accelerate()andbrake(). - Identity: what makes it a separate object, even when its state is the same as another's. Two cars of the same colour and model are still two different cars. In Java, each object has its own place in memory.
Calling a method usually changes the state: after myCar.accelerate(), its speed is higher. That is the basic idea of an object-oriented program: objects keep their own state, and methods change it in controlled ways.
A class is a new type
Java has built-in types such as int, double and boolean. Each class you write is a new type that you can use in the same way:
int age; // a variable of a built-in type
Student nimal; // a variable of your own type, StudentThe class defines what every object of that type has and can do. It is written once, but you can create as many objects from it as you need.
Finding classes in a problem
Read the problem description and look for:
- Nouns (things): candidate classes or attributes. "A library lends books to members" gives the classes Library, Book and Member.
- Describing words (properties): attributes. "Each book has a title, an author and an ISBN."
- Verbs (actions): methods. "A member borrows and returns books" gives
borrow()andreturnBook().
Not every noun becomes a class. A noun that is just a simple value, such as title or price, is usually an attribute of another class.
Naming conventions in Java
- Class names are nouns in PascalCase:
Student,BankAccount,LibraryMember. - Attribute and variable names are in camelCase:
name,accountNo,totalMarks. - Method names are verbs in camelCase:
deposit(),getGrade(),calculateTotal(). - Constants are in UPPER_CASE:
MAX_SPEED.
These are conventions, not rules: the compiler will accept other names. But every Java programmer follows them, so following them makes your code much easier to read.
Remember
- A class is written once; any number of objects can be created from it.
- Each object has its own state (attribute values), shared behaviour (methods) and its own identity.
- Nouns suggest classes and attributes; verbs suggest methods.