Revisiting Java Classes and Object-Oriented Programming

Revisiting Java Classes and Object-Oriented Programming

Greetings! Today, we're exploring Java classes, the core building block of Object-Oriented Programming (OOP) in Java. Classes play a pivotal role in structuring code to model real-world entities and behaviors. Through hands-on examples, we'll delve into the fundamental concepts of Java classes, including their structure, methods, and encapsulation. This session aims to enhance your understanding of how classes facilitate better code organization and reusability.

Java Classes Refresher

Let's begin with a refresher on Java classes. Essential to OOP, Java classes bundle relevant data and functions into compact units called objects. Consider a video game character, which is a typical example of a class instance, with specific fields (such as health and strength) and methods (such as attack).

class GameCharacter {
    // Fields
    private String name;
    private int health;
    private int strength;

    // Constructor
    public GameCharacter(String name, int health, int strength) {
        this.name = name;
        this.health = health;
        this.strength = strength;
    }

    // Method
    public void attack(GameCharacter otherCharacter) {
        otherCharacter.health -= this.strength;
    }

    // Getter methods
    public String getName() {
        return name;
    }

    public int getHealth() {
        return health;
    }

    public int getStrength() {
        return strength;
    }
}

class Solution {
    public static void main(String[] args) {
        // Example usage
        GameCharacter character1 = new GameCharacter("Hero", 100, 20);
        GameCharacter character2 = new GameCharacter("Villain", 80, 15);

        System.out.println(character2.getHealth()); // Prints: 80
        character1.attack(character2);              // character1 attacks character2
        System.out.println(character2.getHealth()); // Prints: 60
    }
}

In the code above, the GameCharacter class has fields name, health, and strength. Each of these fields is accessed via getter methods, such as getHealth(), which provide a way to access these private fields from outside the class while maintaining encapsulation.

Java classes facilitate the grouping of associated code elements, simplifying their management. Now, let's go through this example step-by-step to better understand how it functions.

Structure of a Java Class

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal