Skip to main content
Published on

Classes and Objects in Java

Share:

Introduction

Java, being an object-oriented language, has its foundation built around the concept of classes and objects. In this article, we will explore these fundamental concepts and how they interrelate in building robust applications.

What are Classes?

Classes in Java can be thought of as templates or blueprints for creating objects. They encapsulate the data for the object and the methods to operate on that data.

  • Attributes: Represent the properties of an object. For example, a car has colour, make, and model as attributes.
  • Methods: Represent the behaviour. Continuing with the car example, the methods could be start(), brake(), and accelerate().

What are Objects?

An object is an instance of a class. When we create an object, we are essentially creating an instance of that class, endowed with its own state and behaviour.

Fundamental OOP Concepts

  1. Encapsulation: Refers to the bundling of data (attributes) and methods that operate on that data into a single unit (i.e., a class).
  2. Inheritance: Allows a class to inherit attributes and methods from another class. This promotes code reuse.
  3. Polymorphism: The ability of an object to take on many forms. Polymorphism in Java is achieved through method overloading and overriding.

Practical Example

Let's consider an example where we have a class that represents an "Enemy" in a game.

package com.caffeinealgorithm.programaremjava;

public class ClassesAndObjects {
  private int lives = 5;

  public void attack() {
    System.out.println("I was attacked and lost a life.");
    lives -= 1;
  }

  public void checkLife() {
    if (lives <= 0)
      System.out.println("I am dead because I have no more lives.");
    else
      System.out.printf("I am still in combat and have %d lives.\n", lives);
  }
}

In the example above, the ClassesAndObjects class has a lives attribute and two methods, attack() and checkLife().

package com.caffeinealgorithm.programaremjava;

public class Main {
  public static void main(String[] args) {
    var enemy1 = new ClassesAndObjects();
    var enemy2 = new ClassesAndObjects();

    enemy1.attack(); // I was attacked and lost a life.
    enemy1.attack(); // I was attacked and lost a life.
    enemy1.attack(); // I was attacked and lost a life.
    enemy1.checkLife(); // I am still in combat and have 2 lives.
    enemy2.checkLife(); // I am still in combat and have 5 lives.
  }
}

Conclusion

Classes and objects are pillars of the object-oriented programming paradigm in Java. Understanding how they work together is essential for writing efficient and scalable Java programs.

Happy coding!