Chapter 3

Object-Oriented Programming

Starting from this lesson you’ll be studying various elements of the Java language with brief descriptions to get you started programming in the shortest possible time. But you are certainly encouraged to refer to the extensive Java documentation that’s available online at

Classes and Objects

Java is an object-oriented language, which means that it has constructs to represent objects from the real world. Each Java program has at least one class that knows how to do certain things or how to represent some type of object. For example, the simplest class, HelloWorld, knows how to greet the world.

Classes in Java may have methods (aka functions) and fields (aka attributes or properties).

Let’s create and discuss a class named Car. This class will have methods, describing what this type of vehicle can do, such as start the engine, shut it down, accelerate, brake, lock the doors, and so on.

This class will also have some fields: body color, number of doors, sticker price, and so on.


Listing 3-1: Class Car

class Car{
    String color;
    int numberOfDoors;
    void startEngine {
       // Some code goes here
    void stopEngine {
         int tempCounter=0;  
      // Some code goes here

Lines that start with double slashes are comments, which will be explained later in this lesson.

Car ...

Get Java® Programming 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.