Skip to content
IRC-Coding IRC-Coding
OOP concepts Attributes Messages Method calls Persistence Interfaces API

OOP Concepts: Attributes, Messages, Methods & Interfaces

Learn essential OOP concepts: attributes, method calls, data persistence, and interfaces with practical code examples.

S

schutzgeist

2 min read
OOP Concepts: Attributes, Messages, Methods & Interfaces

OOP Terms: Attributes, Messages, Method Calls, Persistence & Interfaces

This article is a comprehensive explanation of the most important OOP concepts – including attributes, messages, method calls, persistence and interfaces with practical examples.

In a Nutshell

OOP terms describe the fundamental concepts of object-oriented programming: attributes as properties, messages as communication, persistence as data storage and interfaces as contracts.

Compact Technical Description

Object-oriented programming (OOP) uses specific terms to describe concepts and structures.

Attribute (Attribute/Field/Property)

An attribute is a property or a state of an object. It describes data that an object contains.

Characteristics:

  • Data type: Defines the type of data (String, int, boolean, etc.)
  • Visibility: public, private, protected, package
  • Value: Current state of the property
  • Lifetime: Exists as long as the object exists

Message (Message/Method Call)

A message is the communication between objects. It instructs an object to perform a specific action.

Components:

  • Receiver: Object that receives the message
  • Selector: Name of the method to be called
  • Arguments: Parameters for the method
  • Return value: Result of the operation

Persistence (Persistence)

Persistence refers to the durability of data beyond the program runtime.

Types of persistence:

  • File system: Serialization in files
  • Databases: Relational or NoSQL databases
  • Cloud storage: External storage services
  • In-Memory: Temporary persistence

Interface (Interface/API)

An interface defines a contract between components and describes which operations are available.

Types of interfaces:

  • Programming interfaces: Method signatures
  • Web APIs: HTTP endpoints
  • User interfaces: GUI components
  • Hardware interfaces: Device drivers

Exam-Relevant Key Points

  • Attributes: Properties/data of objects with visibility
  • Messages: Communication between objects via method call
  • Method call: Execution of operations on objects
  • Persistence: Permanent data storage beyond program runtime
  • Interfaces: Contracts between components, defined APIs
  • Encapsulation: Data and methods as a unit
  • Abstraction: Reduce complexity through simplification
  • IHK-relevant: Fundamental understanding for OOP development

Core Components

  1. Attributes: Data properties of objects
  2. Messages: Object communication
  3. Methods: Behavior implementation
  4. Persistence: Data durability
  5. Interfaces: Defined contracts
  6. Encapsulation: Data and method bundling
  7. Abstraction: Complexity reduction
  8. Polymorphism: Multiple forms of an interface

Practical Examples

1. Attributes in different languages

// Java Attribute
public class Auto {
    // Instanzattribute (pro Objekt)
    private String marke;           // Private Eigenschaft
    protected int baujahr;          // Geschützte Eigenschaft
    public double preis;            // Öffentliche Eigenschaft
    
    // Klassenattribut (für alle Objekte gleich)
    private static int anzahlAutos = 0;
    
    // Konstante
    public static final int MAX_GESCHWINDIGKEIT = 250;
    
    // Konstruktor zur Initialisierung
    public Auto(String marke, int baujahr, double preis) {
        this.marke = marke;
        this.baujahr = baujahr;
        this.preis = preis;
        Auto.anzahlAutos++; // Klassenattribut erhöhen
    }
    
    // Getter und Setter für gekapselte Attribute
    public String getMarke() {
        return marke;
    }
    
    public void setMarke(String marke) {
        this.marke = marke;
    }
    
    public static int getAnzahlAutos() {
        return anzahlAutos;
    }
}
// C# Attribute
public class Mitarbeiter
{
    // Auto-Properties (moderne Syntax)
    public string Name { get; set; }
    public int Alter { get; private set; }  // Nur lesbar von außen
    
    // Volle Property mit Validierung
    private double gehalt;
    public double Gehalt
    {
        get { return gehalt; }
        set
        {
            if (value >= 0)
                gehalt = value;
            else
                throw new ArgumentException("Gehalt kann nicht negativ sein");
        }
    }
    
    // Statische Eigenschaft
    public static string Firma { get; set; } = "TechCorp";
    
    // Konstante
    public const decimal MINDESTGEHALT = 2000m;
    
    public Mitarbeiter(string name, int alter, double gehalt)
    {
        Name = name;
        Alter = alter;
        Gehalt = gehalt;
    }
}
# Python Attribute
class Person:
    # Klassenattribut
    anzahl_personen = 0
    
    def __init__(self, name, alter):
        # Instanzattribute
        self.name = name          # Öffentlich
        self._alter = alter       # Geschützt (Konvention)
        self.__geheim = "data"    # Privat (Name Mangling)
        
        Person.anzahl_personen += 1
    
    # Property für gekapselten Zugriff
    @property
    def alter(self):
        return self._alter
    
    @alter.setter
    def alter(self, wert):
        if wert >= 0:
            self._alter = wert
        else:
            raise ValueError("Alter kann nicht negativ sein")
    
    # Statische Methode
    @staticmethod
    def get_anzahl_personen():
        return Person.anzahl_personen

2. Messages and method calls

// Messages between objects
public class Bankkonto {
    private double kontostand;
    private String kontonummer;
    
    public Bankkonto(String kontonummer, double startbetrag) {
        this.kontonummer = kontonummer;
        this.kontostand = startbetrag;
    }
    
    // Method to receive messages
    public void einzahlen(double betrag) {
        if (betrag > 0) {
            this.kontostand += betrag;
            System.out.println("Einzahlung: " + betrag + "€, neuer Kontostand: " + kontostand + "€");
        }
    }
    
    public boolean abheben(double betrag) {
        if (betrag > 0 && kontostand >= betrag) {
            kontostand -= betrag;
            System.out.println("Abhebung: " + betrag + "€, neuer Kontostand: " + kontostand + "€");
            return true;
        }
        return false;
    }
    
    public double getKontostand() {
        return kontostand;
    }
    
    public String getKontonummer() {
        return kontonummer;
    }
}

// Customer sends messages to bank account
public class Kunde {
    private String name;
    private Bankkonto konto;
    
    public Kunde(String name, Bankkonto konto) {
        this.name = name;
        this.konto = konto;
    }
    
    // Customer sends messages to their account
    public void geldEinzahlen(double betrag) {
        System.out.println(name + " will " + betrag + "€ einzahlen");
        konto.einzahlen(betrag);  // Send message
    }
    
    public boolean geldAbheben(double betrag) {
        System.out.println(name + " will " + betrag + "€ abheben");
        return konto.abheben(betrag);  // Send message
    }
    
    public void kontostandPruefen() {
        double stand = konto.getKontostand();  // Send message
        System.out.println(name + "'s Kontostand: " + stand + "€");
    }
}

// Usage of messages
public class BankingDemo {
    public static void main(String[] args) {
        Bankkonto konto = new Bankkonto("DE123456789", 1000.0);
        Kunde kunde = new Kunde("Max Mustermann", konto);
        
        // Message chain
        kunde.geldEinzahlen(500.0);
        kunde.kontostandPruefen();
        
        if (kunde.geldAbheben(200.0)) {
            System.out.println("Abhebung erfolgreich");
        }
        
        kunde.kontostandPruefen();
    }
}

3. Persistence Implementation

// Serialization for file persistence
import java.io.*;
import java.util.*;

public class PersistenzDemo {
    
    // Serializable class
    static class Produkt implements Serializable {
        private static final long serialVersionUID = 1L;
        
        private String id;
        private String name;
        private double preis;
        private transient Date lastModified; // transient = not serialized
        
        public Produkt(String id, String name, double preis) {
            this.id = id;
            this.name = name;
            this.preis = preis;
            this.lastModified = new Date();
        }
        
        // Getters and toString
        public String getId() { return id; }
        public String getName() { return name; }
        public double getPreis() { return preis; }
        
        @Override
        public String toString() {
            return String.format("Produkt[id=%s, name=%s, preis=%.2f]", id, name, preis);
        }
    }
    
    // Persistence manager
    static class PersistenzManager {
        private String dateiname;
        
        public PersistenzManager(String dateiname) {
            this.dateiname = dateiname;
        }
        
        // Save objects
        public void speichereProdukte(List<Produkt> produkte) throws IOException {
            try (ObjectOutputStream oos = new ObjectOutputStream(
                    new FileOutputStream(dateiname))) {
                oos.writeObject(produkte);
                System.out.println("Products saved in " + dateiname);
            }
        }
        
        // Load objects
        @SuppressWarnings("unchecked")
        public List<Produkt> ladeProdukte() throws IOException, ClassNotFoundException {
            try (ObjectInputStream ois = new ObjectInputStream(
                    new FileInputStream(dateiname))) {
                List<Produkt> produkte = (List<Produkt>) ois.readObject();
                System.out.println("Products loaded from " + dateiname);
                return produkte;
            }
        }
    }
    
    // JSON persistence (manual)
    static class JsonPersistenz {
        public static void speichereAlsJson(List<Produkt> produkte, String dateiname) throws IOException {
            try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(dateiname))) {
                writer.write("[\n");
                for (int i = 0; i < produkte.size(); i++) {
                    Produkt p = produkte.get(i);
                    writer.write(String.format(
                        "  {\"id\": \"%s\", \"name\": \"%s\", \"preis\": %.2f}",
                        p.getId(), p.getName(), p.getPreis()
                    ));
                    if (i < produkte.size() - 1) {
                        writer.write(",\n");
                    }
                }
                writer.write("\n]");
            }
            System.out.println("Products saved as JSON");
        }
    }
    
    public static void main(String[] args) {
        List<Produkt> produkte = Arrays.asList(
            new Produkt("P001", "Laptop", 999.99),
            new Produkt("P002", "Maus", 29.99),
            new Produkt("P003", "Tastatur", 79.99)
        );
        
        PersistenzManager manager = new PersistenzManager("produkte.ser");
        
        try {
            // Serialization
            manager.speichereProdukte(produkte);
            
            // Deserialization
            List<Produkt> geladeneProdukte = manager.ladeProdukte();
            geladeneProdukte.forEach(System.out::println);
            
            // JSON persistence
            JsonPersistenz.speichereAlsJson(produkte, "produkte.json");
            
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

4. Interfaces and APIs

// Programming interface (Interface)
interface DatenbankSchnittstelle {
    // Abstract methods (without implementation)
    void verbinden() throws DatenbankException;
    void trennen();
    boolean istVerbunden();
    
    // Query methods
    List<Map<String, Object>> abfragen(String sql) throws DatenbankException;
    int ausfuehren(String sql) throws DatenbankException;
    
    // Default methods (since Java 8)
    default void verbindenMitTimeout(int timeout) throws DatenbankException {
        verbinden(); // Standard implementation
    }
}

// Custom exception class
class DatenbankException extends Exception {
    public DatenbankException(String nachricht) {
        super(nachricht);
    }
    
    public DatenbankException(String nachricht, Throwable ursache) {
        super(nachricht, ursache);
    }
}

// Concrete implementation
class MySQLDatenbank implements DatenbankSchnittstelle {
    private boolean verbunden = false;
    private String verbindungsString;
    
    public MySQLDatenbank(String verbindungsString) {
        this.verbindungsString = verbindungsString;
    }
    
    @Override
    public void verbinden() throws DatenbankException {
        try {
            // Simulated connection
            System.out.println("Connecting to MySQL: " + verbindungsString);
            Thread.sleep(1000); // Simulate network delay
            verbunden = true;
            System.out.println("Connection established");
        } catch (InterruptedException e) {
            throw new DatenbankException("Connection interrupted", e);
        }
    }
    
    @Override
    public void trennen() {
        if (verbunden) {
            System.out.println("Connection closed");
            verbunden = false;
        }
    }
    
    @Override
    public boolean istVerbunden() {
        return verbunden;
    }
    
    @Override
    public List<Map<String, Object>> abfragen(String sql) throws DatenbankException {
        if (!verbunden) {
            throw new DatenbankException("Not connected");
        }
        
        System.out.println("Execute: " + sql);
        
        // Simulated result
        List<Map<String, Object>> ergebnis = new ArrayList<>();
        Map<String, Object> zeile = new HashMap<>();
        zeile.put("id", 1);
        zeile.put("name", "Test data");
        ergebnis.add(zeile);
        
        return ergebnis;
    }
    
    @Override
    public int ausfuehren(String sql) throws DatenbankException {
        if (!verbunden) {
            throw new DatenbankException("Not connected");
        }
        
        System.out.println("Execute: " + sql);
        return 1; // Simulated affected rows
    }
}

// API usage
public class ApiDemo {
    public static void main(String[] args) {
        // Polymorphic usage via interface
        DatenbankSchnittstelle db = new MySQLDatenbank("jdbc:mysql://localhost/test");
        
        try {
            // Work through the interface
            db.verbinden();
            
            if (db.istVerbunden()) {
                List<Map<String, Object>> ergebnis = db.abfragen("SELECT * FROM kunden");
                System.out.println("Result: " + ergebnis.size() + " rows");
                
                int rows = db.ausfuehren("UPDATE kunden SET status = 'active'");
                System.out.println("Affected rows: " + rows);
            }
            
        } catch (DatenbankException e) {
            System.err.println("Database error: " + e.getMessage());
        } finally {
            db.trennen();
        }
    }
}

5. Web API Example

// REST API Controller (Spring Boot Example)
@RestController
@RequestMapping("/api/kunden")
public class KundenAPI {
    
    private final KundenService service;
    
    public KundenAPI(KundenService service) {
        this.service = service;
    }
    
    // GET /api/kunden/{id}
    @GetMapping("/{id}")
    public ResponseEntity<Kunde> getKunde(@PathVariable Long id) {
        try {
            Kunde kunde = service.findeKundeById(id);
            return ResponseEntity.ok(kunde);
        } catch (KundeNotFoundException e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    // POST /api/kunden
    @PostMapping
    public ResponseEntity<Kunde> createKunde(@RequestBody Kunde kunde) {
        Kunde erstellterKunde = service.erstelleKunde(kunde);
        return ResponseEntity.status(HttpStatus.CREATED).body(erstellterKunde);
    }
    
    // PUT /api/kunden/{id}
    @PutMapping("/{id}")
    public ResponseEntity<Kunde> updateKunde(@PathVariable Long id, @RequestBody Kunde kunde) {
        try {
            Kunde aktualisierterKunde = service.aktualisiereKunde(id, kunde);
            return ResponseEntity.ok(aktualisierterKunde);
        } catch (KundeNotFoundException e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    // DELETE /api/kunden/{id}
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteKunde(@PathVariable Long id) {
        service.loescheKunde(id);
        return ResponseEntity.noContent().build();
    }
}

// Data model
class Kunde {
    private Long id;
    private String name;
    private String email;
    private LocalDate geburtsdatum;
    
    // Getter and Setter
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    public LocalDate getGeburtsdatum() { return geburtsdatum; }
    public void setGeburtsdatum(LocalDate geburtsdatum) { this.geburtsdatum = geburtsdatum; }
}

Keine Bücher für Kategorie "objektorientierte-programmierung" gefunden.

OOP Concepts at a Glance

Encapsulation

// Data and methods are encapsulated into a unit
public class Bankkonto {
    private double kontostand;  // Private data
    
    public void einzahlen(double betrag) {  // Public method
        if (betrag > 0) {
            kontostand += betrag;
        }
    }
    
    public double getKontostand() {
        return kontostand;
    }
}

Abstraction

// Complex reality is simplified
abstract class Fahrzeug {
    protected String marke;
    
    public abstract void beschleunigen();
    public abstract void bremsen();
    
    public void anzeigen() {
        System.out.println("Fahrzeug: " + marke);
    }
}

Polymorphism

// One interface, many implementations
interface Tier {
    void macheLaut();
}

class Hund implements Tier {
    public void macheLaut() {
        System.out.println("Wuff!");
    }
}

class Katze implements Tier {
    public void macheLaut() {
        System.out.println("Miau!");
    }
}

// Usage
Tier tier1 = new Hund();
Tier tier2 = new Katze();

tier1.macheLaut(); // Wuff!
tier2.macheLaut(); // Miau!

Persistence Strategies

Serialization

  • Java Serialization: Serializable Interface
  • JSON: Human-readable, platform-independent
  • XML: Structured, with metadata
  • Binary: Compact, fast

Database Persistence

  • Relational DB: Structured data with SQL
  • NoSQL DB: Flexible documents or key-value
  • ORM: Object-Relational Mapping
  • JPA/Hibernate: Java Persistence API

Cloud Persistence

  • Object Storage: S3, Azure Blob Storage
  • Databases-as-a-Service: Firebase, Supabase
  • Caching: Redis, Memcached

API Types

Programming Interfaces

  • Local APIs: Methods in same program
  • Library APIs: Third-party libraries
  • Framework APIs: Spring, Django, React

Web APIs

  • REST: HTTP methods, status codes
  • GraphQL: Flexible query language
  • gRPC: High-performance RPC
  • WebSocket: Real-time communication

Platform APIs

  • OS APIs: Windows, Linux, macOS
  • Mobile APIs: Android, iOS
  • Cloud APIs: AWS, Azure, GCP

Advantages and Disadvantages

Advantages of OOP Concepts

  • Structuring: Clear organization of code
  • Reusability: Components can be reused
  • Maintainability: Modular structure facilitates changes
  • Testability: Isolated components are easy to test
  • Scalability: Systems can grow

Disadvantages

  • Complexity: Overhead in small projects
  • Learning Curve: Many concepts to understand
  • Performance: Sometimes slower than procedural code
  • Over-Engineering: Risk of excessive complexity

Common Exam Questions

  1. What is the difference between an attribute and a method? Attributes are properties/data, methods are behavior/functions of an object.

  2. Explain the concept of a message in OOP! A message is communication between objects, usually implemented as a method call.

  3. What does persistence mean in programming? Storing data permanently so it remains available beyond program execution.

  4. What is the purpose of interfaces? Define contracts between components and enable loose coupling and polymorphism.

Most Important Sources

  1. https://en.wikipedia.org/wiki/Object-oriented_programming
  2. https://docs.oracle.com/javase/tutorial/java/concepts/
  3. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/
Back to Blog
Share:

Related Posts