Unit 3 · OOP Concepts

3.1.1Classes and objects in the real world

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)
CarmyCar, yourCarcolour, model, speedstart(), accelerate(), brake()
StudentNimal, Kamalaname, indexNo, marksstudy(), getGrade()
BankAccountaccount 101, account 102accountNo, balancedeposit(), withdraw()
DogRex, Bellaname, breed, agebark(), 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.

Carcolour: Stringmodel: Stringspeed: intstart()accelerate(int)brake(int)class = blueprintmyCar : Carcolour"Red"model"Axio"speed0yourCar : Carcolour"Blue"model"Vitz"speed40new Car()new Car()objects = instances, each with its own state
One class (the blueprint) is used with new to create many objects, each with its own attribute values

State, behaviour and identity

Every object has three characteristics:

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:

Java
int age;          // a variable of a built-in type
Student nimal;    // a variable of your own type, Student

The 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:

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

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.