Java Fundamentals – Object-Orientated Programming

In this article, we are going to cover some of the fundamental topics around Object-Orientated Programming (OOP). This will be the first of many non-exhaustive, beginner friendly lessons. I will cover the more advanced topics in a separate article, but I will briefly address them here so you are aware of them. If you haven’t already done so I would recommend you check out this article to get setup with a JDK and an IDE (you can’t start writing Java code without these), as well as this article to setup version control with Git and GitHub.

This is what we’re going to cover:

Object-Oriented Programming (OOP)

OOP is an approach to writing computer programmes (also known as a programming paradigm) that uses objects and classes for organising code and modeling real-world things (like pets, students, or application forms, etc.). It is a fundamental concept in software development that promotes modularity (breaking something complex into smaller components), reusability, and maintainability.

What Is An Object?

An object is like a thing or an entity that exists in the real world. It can be anything, like a toy, a car, or a person. Objects have two distinct characteristics – properties (data/ attributes/ information) and actions (functions/ methods).

Properties/ Attributes

Attributes are the characteristics or properties that define an object. They provide specific details about an object and help distinguish it from others.

To illustrate this, let’s consider a few examples. For a toy, its attributes may include its color, size, recommended age range, shape, and so on. These attributes collectively describe the toy and differentiate it from other toys.

Similarly, for a person, attributes could include their hair colour, height, weight, favourite colour, and more. These attributes help create a unique profile for the person and contribute to their overall identity.

Actions/ Methods

Objects can do things. For example, if you have a Robot object, its actions could include walk, talk, and dance. Think of these actions as tasks that an object knows how to do.

What Is A Class?

A class is like a blueprint or a template for creating objects. It defines the structure (attributes) and behaviour (methods) that the objects created from it will have.

Java Object And Class Example

Here’s a simple Java class and object example that represents a “Person” with a name and an age. This person can also say hello through a defined action (method):

Person Class
// Define a class called Person
public (1) class (2) Person (3)  {
    // Attributes (data) of the Person class
    private (4) String (5) name (6);
    private int age;
   
   public Person(String name, int age) {  (7)
        this.name = name;
        this.age = age;
    }
   public Person(){}  (8)
    // getter and setter methods
    public String (9) getName (10)(){
        return this.name;
    }
    public void (11) setName(String name (12)){
        this.name = name;
    }
    public int getAge(){
        return this.age;
    }
    public void setAge(int age){
        this.age = age;
    }
    // Method for the person to say hello
    public void sayHello() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }
}
Code Breakdown

  1. Public is what’s known as an access modifier. It is used to define the visibility of a class, variable or method. When something is declared as public, it means it can be accessed and used from anywhere within the programme.
  2. Class is a fundamental keyword in many programming languages. It is used to declare and define a new class.
  3. Person is the name of the class. It is user-defined (i.e., you set it) and represents the blueprint for creating objects of this class.
  4. Private is another access modifier. It sets the attribute to private, meaning it cannot be accessed directly from outside the class.
  5. String is the data type of the attribute “name”. We give all of our attributes a data type. Don’t worry if this doesn’t make sense at the minute, we’re going to cover it in a below section.
  6. Name is just a reference we give to some data. For best practice, make it as accurate as possible. For example if you wanted to collect the Person’s email address, you could write the following code: private String emailAddress;
  7. Parameterised Constructor, aka an AllArgsConstructor, is a special type of method that we use to create objects. We pass in the data that we need to create the object with as parameters. We don’t explicitly need one as we can use a default constructor (point 8). However, if we provide a parameterised constructor and omit a default constructor, then we need to pass in data to create the object. Constructor names need to be the same as the class name.
  8. Default Constructor is created by the compiler by default. We can use this when we maybe don’t have all the data when creating the object and can assign it later using ‘setter‘ methods.
  9. Method Return Type refers to the data type that a method will return. I.e., String, int, Boolean, etc.
  10. Method Name is the meaningful name that we assign to a method. As a good practice, at a glance, a developer should have a rough idea of what the method does by reading the name and without looking at the code. So ‘getName’ we could assume that this method will get the Person’s (the objects) name.
  11. Void is a key word reserved for a method that does not return anything.
  12. Parameters are data that we pass to method, and the method does something with them. For example, we could pass a list of Person objects and the method’s job could be to find everyone named ‘Bob’.
Main Class
public class Main {
    public static void main(String[] args) {
        // Create an object (instance) of the 
        // Person class
        Person person1 = new (1) Person();
        // Set attributes for the person 
        // object via setter methods
        person1.setName("Alice");
        person1.setAge(30);
        // Call the introduce method 
        // to introduce the person
        person1.introduce();
        // Create another person 
        // object via the parameterised 
        // constructor
        Person person2 = new Person("Bob", 25);
        // Call the introduce method 
        // to introduce the person
        person2.introduce();
    }
}

Code Breakdown
  1. new is a keyword that is reserved in Java to create an instance of a class.
The Four Pillars Of OOP

There are four key principles or pillars that make up OOP. However, I won’t go into a lot of detail as I could probably write an article on each of them (maybe I’ll do that in the future!):

Encapsulation

The primary purpose of encapsulation is to restrict direct access to certain parts of an object and to prevent unintended interference or modification.

Imagine you have a box, and inside that box you have lots of other smaller boxes, and some of the smaller boxes are locked, and some are open. In terms of OOP, the boxes represent attributes, and the BIG box represents a class. The open boxes are public and the closed boxes are private. By making things public or private we can restrict how parts of our application can interact with that class, giving us more protection and control.

Inheritance

Inheritance allows classes to inherit properties (attributes and methods) of another class.

Think of you and your parents. Your parents are the superclass or base class, and you are the subclass or the derived class. You can inherit things from your parents like, eye colour, hair colour, etc. But, you can also have your own unique properties. Inheritance enables code reuse, and promotes modularity. In Java a class can only inherit from one other class by using the extends keyword.

// Parent class or superclass
class Animal {
    public void eat() {
        System.out.println("The animal is eating.");
    }
}
// Child class or subclass inheriting from Animal
class Dog extends Animal {
    public void bark() {
        System.out.println("The dog is barking.");
    }
}
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.eat(); // Inherited method from Animal class
        dog.bark(); // Method specific to Dog class
    }
}
Polymorphism

Polymorphism allows objects of different classes to be treated as if they belong to the same superclass or parent class. This promotes more flexible and reusable code.

Imagine we wrote a programme for Transformers (Autobots, transform and roll out!). Well Autobots are always changing. One minute they could be a car, next a motorbike, etc. All of these types of vehicles have common behaviour, for example “move”. However, each moves in its own way. We could have all of these vehicles (subclasses) inherit from a common Transformer class/ interface (superclass), and each subclass can have its own implementation of a “move” method.

// Common superclass
interface Transformer {
    public void move();
}
// Subclasses inheriting from Transformer 
class Car implements Transformer {
    @Override
    public void move() {
        System.out.println("The car is driving on the road.");
    }
}
class Bicycle implements Transformer {
    @Override
    public void move() {
        System.out.println("The bicycle is pedaling on the road.");
    }
}
class Motorcycle implements Transformer {
    @Override
    public void move() {
        System.out.println("The motorcycle is accelerating on the road.");
    }
}
public class Main {
    public static void main(String[] args) {
        Transformer transformer1 = new Car(); // Polymorphic assignment
        Transformer transformer2 = new Bicycle(); // Polymorphic assignment
        Transformer transformer3 = new Motorcycle(); // Polymorphic assignment
        transformer1.move(); // Calls the move() method of Car
        transformer2.move(); // Calls the move() method of Bicycle
        transformer3.move(); // Calls the move() method of Motorcycle
    }
}

While we haven’t discussed interfaces yet, it’s worth mentioning a useful tip. In Java, a class can only extend one other class, but it can implement multiple interfaces. This means that a class can inherit behaviour from a single class while incorporating functionality from many interfaces.

Abstraction

In programming, this is a concept of hiding away unnecessary details and focusing only on the essential aspects of a system or object.

Lets say you have a television remote and you push the power button. We know that the television will come on, and if you push the volume button, the volume will change. We don’t need to know the inner workings of the remote control, but when we push a button, we know that it will perform an action. That’s abstraction in essence. By concealing complex processes, we can concentrate on the essentials. In Java we can achieve abstraction through the use of abstract classes, abstract methods, and interfaces.

Summary

This article provided a beginner-friendly overview of Object-Oriented Programming (OOP) concepts. It covered the fundamental ideas of objects and classes, and introduces the four pillars of OOP: encapsulation, inheritance, polymorphism, and abstraction. Stay tuned for the next set of articles which will focus more on the Java programming language.

Scroll to Top