Skip to content
IRC-Coding IRC-Coding
OOP Fundamentals Class Object Instance Attributes Methods Inheritance Polymorphism Encapsulation IHK Exam

OOP Fundamentals: Classes, Objects & Methods

Master OOP basics: classes vs objects, attributes, methods, inheritance, polymorphism, encapsulation. IHK exam prep.

S

schutzgeist

2 min read

OOP Fundamentals: Class, Object, Instance & Methods for IHK Exam

Object-oriented programming (OOP) is a fundamental paradigm in modern software development. This learning document prepares you specifically for the IHK exam and explains the core concepts in an understandable way with practical examples.

Why OOP? The Introduction

Imagine you’re building a car. You wouldn’t reinvent every screw, every wheel, and every part each time. You use prefabricated, reusable parts (like tires, seats, engines) that have specific functions and work together. That’s how OOP works too. It’s a programming paradigm that assembles software from reusable, clearly structured “building blocks” – the objects. This makes software more maintainable, expandable, and understandable.

The Central Difference: Class vs. Object (Instance)

This is the foundation. If you understand this, everything else makes sense.

Class (Blueprint)

A class is an abstract blueprint or template. It defines which attributes (properties) and methods (capabilities) the objects created from it will have.

Example: The class Auto. The blueprint says: “A car has the attributes farbe, anzahlTüren and leistungInPS. It can execute the methods bremsen() and beschleunigen().”

The class exists only once in the code.

Object / Instance (concrete thing)

An object is a concrete manifestation (an “instance”) of a class. It is created from the class at runtime of the program (new keyword in languages like Java or C#).

Example: The object meinGolf is an instance of the class Auto. It has the concrete attribute values farbe = "blau", anzahlTüren = 5, leistungInPS = 150. The object deinA3 is a different instance with the values farbe = "schwarz", anzahlTüren = 3, leistungInPS = 120.

Any number of objects can be created from a single class.

Simple Analogy

  • Class = The blueprint for a house (specifies that there are walls, doors, windows)
  • Object = The actually built house (concrete address, wall color is white, the door is made of oak wood)
// Java Example: Class vs Object
public class Auto {
    // Attributes (properties)
    private String farbe;
    private int anzahlTueren;
    private int leistungInPS;
    
    // Constructor
    public Auto(String farbe, int anzahlTueren, int leistungInPS) {
        this.farbe = farbe;
        this.anzahlTueren = anzahlTueren;
        this.leistungInPS = leistungInPS;
    }
    
    // Methods (capabilities)
    public void beschleunigen() {
        System.out.println("Das " + farbe + "e Auto beschleunigt");
    }
    
    public void bremsen() {
        System.out.println("Das " + farbe + "e Auto bremst");
    }
    
    // Getter and Setter
    public String getFarbe() { return farbe; }
    public void setFarbe(String farbe) { this.farbe = farbe; }
    public int getAnzahlTueren() { return anzahlTueren; }
    public int getLeistungInPS() { return leistungInPS; }
}

// Create objects (instantiation)
public class Main {
    public static void main(String[] args) {
        // Object 1
        Auto meinGolf = new Auto("blau", 5, 150);
        meinGolf.beschleunigen();
        
        // Object 2
        Auto deinA3 = new Auto("schwarz", 3, 120);
        deinA3.bremsen();
        
        System.out.println("Mein Golf: " + meinGolf.getFarbe() + ", " + 
                          meinGolf.getAnzahlTueren() + " Türen, " + 
                          meinGolf.getLeistungInPS() + " PS");
    }
}

The Four Principles (Pillars) of OOP

1. Encapsulation

What is it? The bundling of data (attributes) and the code that manipulates this data (methods) into a single unit – the class. Access to the data is controlled by “hiding” it from the outside.

How does it work? Attributes are usually declared as private. This means that from outside the class, no one can directly access meinGolf.leistungInPS or change it. Access is exclusively through public methods, called getters and setters (also called accessor methods).

  • getLeistungInPS(): Returns the value (reading)
  • setLeistungInPS(int neueLeistung): Changes the value (writing)

Why is this so important?

  • Control: The class can check in the set method whether the new value makes sense (e.g., neueLeistung must not be negative)
  • Maintainability: If the internal representation changes (e.g., you suddenly store power in kW instead of PS), you only need to modify the getter/setter methods, not the entire code that retrieves these values
  • Data consistency: Prevents objects from being set to an invalid state
// Example of Encapsulation
public class Bankkonto {
    // Private attributes - not accessible from outside
    private double kontostand;
    private String kontonummer;
    private String inhaber;
    
    public Bankkonto(String kontonummer, String inhaber, double startbetrag) {
        this.kontonummer = kontonummer;
        this.inhaber = inhaber;
        this.kontostand = Math.max(0, startbetrag); // Kontostand darf nicht negativ sein
    }
    
    // Getter - controlled read access
    public double getKontostand() {
        return kontostand;
    }
    
    // Setter - controlled write access with validation
    public void setKontostand(double neuerKontostand) {
        if (neuerKontostand >= 0) {
            this.kontostand = neuerKontostand;
        } else {
            System.out.println("Fehler: Kontostand darf nicht negativ sein!");
        }
    }
    
    // Business method with encapsulation
    public void hebeGeldAb(double betrag) {
        if (betrag > 0 && kontostand >= betrag) {
            kontostand -= betrag;
            System.out.println("Abhebung erfolgreich. Neuer Kontostand: " + kontostand);
        } else {
            System.out.println("Abhebung nicht möglich. Ungültiger Betrag oder unzureichendes Guthaben.");
        }
    }
    
    public void zahleEin(double betrag) {
        if (betrag > 0) {
            kontostand += betrag;
            System.out.println("Einzahlung erfolgreich. Neuer Kontostand: " + kontostand);
        } else {
            System.out.println("Einzahlung nicht möglich. Betrag muss positiv sein.");
        }
    }
}

2. Inheritance

What is it? A way to define a new class (child class or subclass) based on an already existing class (parent class or superclass). The child class inherits all attributes and methods of the parent class.

Why do this? To avoid code repetition (DRY principle: Don’t Repeat Yourself) and to represent hierarchical relationships.

Example:

  • Superclass: Fahrzeug (with attributes geschwindigkeit, hersteller and method bewege())
  • Subclass: Auto (inherits from Fahrzeug and adds its own attribute anzahlTüren)
  • Subclass: Fahrrad (inherits from Fahrzeug and adds its own attribute anzahlGänge)

An Auto object automatically has geschwindigkeit and can call bewege().

// Example of Inheritance
// Superclass (base class)
public class Fahrzeug {
    protected String hersteller;
    protected int geschwindigkeit;
    protected int baujahr;
    
    public Fahrzeug(String hersteller, int baujahr) {
        this.hersteller = hersteller;
        this.baujahr = baujahr;
        this.geschwindigkeit = 0;
    }
    
    public void beschleunigen(int increment) {
        this.geschwindigkeit += increment;
        System.out.println(hersteller + " beschleunigt auf " + geschwindigkeit + " km/h");
    }
    
    public void bremsen(int decrement) {
        this.geschwindigkeit = Math.max(0, geschwindigkeit - decrement);
        System.out.println(hersteller + " bremst auf " + geschwindigkeit + " km/h");
    }
    
    public void bewege() {
        System.out.println("Das " + hersteller + " Fahrzeug bewegt sich mit " + geschwindigkeit + " km/h");
    }
    
    // Getter
    public String getHersteller() { return hersteller; }
    public int getGeschwindigkeit() { return geschwindigkeit; }
    public int getBaujahr() { return baujahr; }
}

// Subclass 1
public class Auto extends Fahrzeug {
    private int anzahlTueren;
    private String kraftstoffart;
    
    public Auto(String hersteller, int baujahr, int anzahlTueren, String kraftstoffart) {
        super(hersteller, baujahr); // Call the superclass constructor
        this.anzahlTueren = anzahlTueren;
        this.kraftstoffart = kraftstoffart;
    }
    
    // Own method of the subclass
    public void hupen() {
        System.out.println("Das " + hersteller + " Auto hupt!");
    }
    
    // Override method of the superclass
    @Override
    public void bewege() {
        System.out.println("Das " + anzahlTueren + "-türige " + hersteller + 
                          " Auto fährt auf der Straße mit " + geschwindigkeit + " km/h");
    }
    
    // Getter
    public int getAnzahlTueren() { return anzahlTueren; }
    public String getKraftstoffart() { return kraftstoffart; }
}

// Subclass 2
public class Fahrrad extends Fahrzeug {
    private int anzahlGaenge;
    private String fahrzeugtyp = "Fahrrad";
    
    public Fahrrad(String hersteller, int baujahr, int anzahlGaenge) {
        super(hersteller, baujahr);
        this.anzahlGaenge = anzahlGaenge;
    }
    
    // Own method
    public void schalten(int gang) {
        if (gang >= 1 && gang <= anzahlGaenge) {
            System.out.println("Schalte in Gang " + gang);
        } else {
            System.out.println("Ungültiger Gang!");
        }
    }
    
    // Override method
    @Override
    public void bewege() {
        System.out.println("Das " + hersteller + " Fahrrad mit " + anzahlGaenge + 
                          " Gängen bewegt sich mit " + geschwindigkeit + " km/h");
    }
}

3. Polymorphism (Polymorphic Behavior)

What is it? The ability for an object of a subclass to also be treated as an object of its superclass. Methods can be overridden in subclasses to implement specific behavior.

Example: The method move() is defined in the superclass Vehicle. In the Car class it is overridden to output “The car drives on the road”. In the Airplane class (which also inherits from Vehicle) it is overridden to output “The airplane flies through the air”.

Advantage: The code that calls the move() method doesn’t need to know which concrete type (Car or Airplane) it is. It simply calls move() on the object of type Vehicle. At runtime, the correct, overridden method of the object’s actual class is automatically executed. This makes the code extremely flexible.

// Example of polymorphism
public class PolymorphismDemo {
    public static void main(String[] args) {
        // Various Vehicle objects
        Vehicle myCar = new Car("VW", 2020, 4, "Petrol");
        Vehicle myBicycle = new Bicycle("Cube", 2021, 21);
        Vehicle myMotorcycle = new Motorcycle("Yamaha", 2019, 600);
        
        // Polymorphism: All are treated as Vehicle
        Vehicle[] vehicles = {myCar, myBicycle, myMotorcycle};
        
        // Dynamic binding: The correct method is called at runtime
        for (Vehicle vehicle : vehicles) {
            vehicle.accelerate(50);
            vehicle.move();  // Calls the overridden method of the respective subclass
            vehicle.brake(20);
            System.out.println("---");
        }
        
        // Type checking and downcasting
        for (Vehicle vehicle : vehicles) {
            if (vehicle instanceof Car) {
                Car car = (Car) vehicle;  // Downcasting
                car.honk();
            } else if (vehicle instanceof Bicycle) {
                Bicycle bicycle = (Bicycle) vehicle;
                bicycle.shift(5);
            }
        }
    }
}

// Additional subclass for the example
class Motorcycle extends Vehicle {
    private int displacement;
    
    public Motorcycle(String manufacturer, int modelYear, int displacement) {
        super(manufacturer, modelYear);
        this.displacement = displacement;
    }
    
    @Override
    public void move() {
        System.out.println("The " + manufacturer + " motorcycle with " + displacement + 
                          " ccm drives at " + speed + " km/h");
    }
    
    public void wheelie() {
        System.out.println("The " + manufacturer + " motorcycle does a wheelie!");
    }
}

4. Abstraction

What is it? The principle of reducing complex reality to the essential properties relevant to the context and hiding unnecessary details.

Example: When you model a car as a Car object, you care about attributes like power and methods like brake(). The details of how the brake actually works (hydraulics, brake pads, etc.) are irrelevant to most programs and are “abstracted away”. You simply call brake().

Abstraction is primarily achieved through two things:

  1. Abstract Classes: Classes that cannot be instantiated but serve only as templates for other classes. They can define abstract methods (methods without a body that the subclass must implement).
  2. Interfaces (Interfaces): See next section.
// Example of abstraction
// Abstract class
public abstract class Animal {
    protected String name;
    protected int age;
    
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // Concrete method
    public void sleep() {
        System.out.println(name + " sleeps.");
    }
    
    public void eat() {
        System.out.println(name + " eats.");
    }
    
    // Abstract methods - must be implemented by subclasses
    public abstract void makeSound();
    public abstract void move();
    
    // Getters
    public String getName() { return name; }
    public int getAge() { return age; }
}

// Concrete subclasses
public class Dog extends Animal {
    private String breed;
    
    public Dog(String name, int age, String breed) {
        super(name, age);
        this.breed = breed;
    }
    
    @Override
    public void makeSound() {
        System.out.println(name + " barks: Woof! Woof!");
    }
    
    @Override
    public void move() {
        System.out.println(name + " runs on four legs.");
    }
    
    public void fetch() {
        System.out.println(name + " fetches the ball.");
    }
}

public class Cat extends Animal {
    private String coatColor;
    
    public Cat(String name, int age, String coatColor) {
        super(name, age);
        this.coatColor = coatColor;
    }
    
    @Override
    public void makeSound() {
        System.out.println(name + " meows: Meow!");
    }
    
    @Override
    public void move() {
        System.out.println(name + " sneaks around.");
    }
    
    public void scratch() {
        System.out.println(name + " scratches the scratching post.");
    }
}

Important OOP Terms

Attribute (Property)

A variable that describes a state or property of an object (e.g. color, age, balance).

Method

A function or procedure defined in a class that describes a behavior of the object (e.g. pay(), printDocument()). A method call (or message) is the request to an object to execute a specific method (e.g. myAccount.withdraw(50)).

Persistence

The permanent storage of the state of objects (their attribute values) so that it persists beyond the program termination. This typically happens in a database or a file. An object itself “lives” only in working memory (RAM) at runtime of the program.

// Example of persistence
import java.io.*;
import java.util.*;

public class PersistenceExample {
    
    // Save object
    public static void saveAccount(BankAccount account, String filename) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) {
            oos.writeObject(account);
            System.out.println("Account was saved to " + filename);
        } catch (IOException e) {
            System.out.println("Error saving: " + e.getMessage());
        }
    }
    
    // Load object
    public static BankAccount loadAccount(String filename) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
            BankAccount account = (BankAccount) ois.readObject();
            System.out.println("Account was loaded from " + filename);
            return account;
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("Error loading: " + e.getMessage());
            return null;
        }
    }
    
    public static void main(String[] args) {
        BankAccount myAccount = new BankAccount("DE123456789", "Max Mustermann", 1000.0);
        myAccount.deposit(500.0);
        
        // Save
        saveAccount(myAccount, "account.ser");
        
        // Load
        BankAccount loadedAccount = loadAccount("account.ser");
        if (loadedAccount != null) {
            System.out.println("Loaded account - Balance: " + loadedAccount.getBalance());
        }
    }
}

// Serializable interface for persistence
class BankAccount implements Serializable {
    private static final long serialVersionUID = 1L;
    
    private double balance;
    private String accountNumber;
    private String owner;
    
    // ... rest of implementation as above
}

Interface / API / Interface

(Warning: This term has two meanings!)

  1. In general: An interface (or API - Application Programming Interface) defines a contract description, what something can do, without saying how it is done. It is a collection of method signatures (name, parameters, return type).

  2. As a language construct (interface): A special language construct in OOP languages that formally defines these contracts. A class that implements an interface must implement all methods defined in it (fill them with code).

The Difference: Class vs. Interface

FeatureClassInterface
What is it?A blueprint for objectsA contract or specification for capabilities
Contains…Implementation (code for methods), attributes, constructorsOnly method signatures (name, parameters, return type) without implementation (no code body)
Keywordsclass, extends (inheritance)interface, implements (implementing)
InheritanceA class can inherit from only one other class (single inheritance)A class can implement multiple interfaces
InstantiationCan be instantiated with new (create objects)CANNOT be instantiated
PurposeImplement state and behaviorPrescribe behavior

Analogy

  • Class = A specific employee: “Max Mustermann, Software Developer” knows the company SAP and can write Java code (implementation)
  • Interface = The job posting: “We are looking for a Java developer with SAP experience.” It lists only the requirements (skills) the applicant must bring
// Interface example
interface Fliegend {
    void fliegen();
    void landen();
}

interface Schwimmend {
    void schwimmen();
    void tauchen();
}

// Class implements multiple interfaces
public class Ente implements Fliegend, Schwimmend {
    private String name;
    
    public Ente(String name) {
        this.name = name;
    }
    
    // Implement interface methods
    @Override
    public void fliegen() {
        System.out.println(name + " fliegt in die Luft");
    }
    
    @Override
    public void landen() {
        System.out.println(name + " landet auf dem Wasser");
    }
    
    @Override
    public void schwimmen() {
        System.out.println(name + " schwimmt elegant");
    }
    
    @Override
    public void tauchen() {
        System.out.println(name + " taucht nach Fischen");
    }
    
    // Own method
    public void quaken() {
        System.out.println(name + " quakt: Quak! Quak!");
    }
}

// Polymorphism with interfaces
public class InterfaceDemo {
    public static void main(String[] args) {
        Ente meineEnte = new Ente("Donald");
        
        // Treat as Ente
        meineEnte.quaken();
        
        // Treat as Fliegend
        Fliegend fliegendeEnte = meineEnte;
        fliegendeEnte.fliegen();
        fliegendeEnte.landen();
        
        // Treat as Schwimmend
        Schwimmend schwimmendeEnte = meineEnte;
        schwimmendeEnte.schwimmen();
        schwimmendeEnte.tauchen();
    }
}

The Difference: Class Library vs. Framework

This is an important conceptual distinction that is often tested.

Class Library (Library / SDK)

  • You control the flow. A library is a collection of pre-built classes and methods that you can use in your code whenever and however you see fit.
  • Analogy: A toolbox. You build a shelf and grab a hammer from the box (Hammerklasse.schlagZu()), then a saw (Saegeklasse.saege()). You determine the order and purpose.
  • Examples: Java Standard Library, Apache Commons, jQuery.

Framework

  • The framework controls the flow. A framework is a fundamental skeleton or structure for a specific type of application. You fill in the predefined places with your code. The framework calls your code (principle of the Hollywood Principle: “Don’t call us, we’ll call you”).
  • Analogy: The framework is a blueprint for an entire house including pre-fabricated walls and pipes. You only need to install the outlets and choose the wallpaper (i.e., enter your code in the predefined methods). The blueprint (the framework) determines the flow.
  • Examples: Spring (Java), .NET Framework, Angular, React (web), JUnit (testing).

In summary: You use a library. You work in a framework.

// Library vs. Framework example

// Library: You call the methods
import java.util.ArrayList;
import java.util.Collections;

public class BibliothekBeispiel {
    public static void main(String[] args) {
        // You determine the flow
        ArrayList<String> namen = new ArrayList<>();
        namen.add("Alice");
        namen.add("Bob");
        namen.add("Charlie");
        
        // You use library methods whenever you want
        Collections.sort(namen);
        System.out.println("Sortierte Namen: " + namen);
    }
}

// Framework: The framework calls your code
// Example with JUnit testing framework
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class FrameworkBeispiel {
    
    @Test  // The framework calls this method
    public void testAddition() {
        // You fill the predefined method with your code
        int result = 2 + 3;
        assertEquals(5, result, "2 + 3 sollte 5 ergeben");
    }
    
    @Test  // Another method that the framework calls
    public void testSubtraction() {
        int result = 10 - 4;
        assertEquals(6, result, "10 - 4 sollte 6 ergeben");
    }
}

Summary for the IHK Exam

  • Class vs. Object: Blueprint vs. concrete thing
  • The 4 principles:
    • Encapsulation: Hide data, provide controlled access
    • Inheritance: Inherit properties and methods, avoid redundancy
    • Polymorphism: Override methods to enable subtype-specific behavior
    • Abstraction: Hide unnecessary details
  • Interface vs. Class: Interface defines what, class defines how
  • Library vs. Framework: You use the library, the framework uses you

Exam-Relevant Concepts

Important Distinctions

ConceptDescriptionExam-Relevant
ClassBlueprint for objects
Object/InstanceConcrete manifestation of a class
AttributeProperty of an object
MethodBehavior of an object
InheritanceCode reuse through hierarchy
PolymorphismDiversity through overriding
EncapsulationData hiding with getter/setter
AbstractionComplexity reduction

Typical Exam Tasks

  1. Explain the difference between class and object
  2. Describe the four OOP principles
  3. Implement a simple inheritance hierarchy
  4. Explain encapsulation with getter/setter methods
  5. Distinguish interface from class
  6. Compare library and framework

These fundamentals are essential for understanding modern software development and form the basis for advanced concepts such as design patterns, frameworks, and architectural principles.

Back to Blog
Share:

Related Posts