Skip to content
IRC-CodingIRC-Coding
OOP conceptsattributesmessagesmethod callspersistenceinterfacesAPI

OOP Concepts: Attributes, Messages & Interfaces

Master key OOP concepts: attributes, method calls, persistence, and interfaces with practical examples.

S

schutzgeist

10 min read
OOP Concepts: Attributes, Messages & Interfaces

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

This guide covers the essential OOP concepts in depth—attributes, messages, method calls, persistence, and interfaces—with practical examples throughout.

In a Nutshell

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

Technical Overview

Object-oriented programming (OOP) uses specific terminology to describe its core concepts and structures.

Attribute (Attribute/Field/Property)

An attribute is a property or state that belongs to an object. It represents the data an object holds.

Key characteristics:

  • Data type: Determines what kind of data is stored (string, int, boolean, etc.)
  • Visibility: public, private, protected, or package-level
  • Value: The current state of the property
  • Lifetime: Exists as long as the object exists

Message (Message/Method Call)

A message is communication between objects. It tells one object to perform a specific action.

Components:

  • Receiver: The object that receives the message
  • Method name: Which operation to invoke
  • Arguments: Parameters passed to the method
  • Return value: The result of the operation

Persistence (Persistence)

Persistence refers to data that survives beyond the program’s execution.

Common forms of persistence:

  • Filesystem: Serializing data to files
  • Databases: Relational or NoSQL systems
  • Cloud storage: External storage services
  • In-memory: Temporary persistence during runtime

Interface (Interface/API)

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

Types of interfaces:

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

Key Study Points

  • Attributes: Data properties of objects with access control
  • Messages: Object-to-object communication via method calls
  • Method calls: Executing operations on objects
  • Persistence: Long-term data storage beyond program lifetime
  • Interfaces: Contracts between components with defined APIs
  • Encapsulation: Bundling data and methods as a unit
  • Abstraction: Hiding complexity through simplification
  • Industry relevance: Fundamental to professional OOP development

Core Components

  1. Attributes: Data properties of objects
  2. Messages: Communication between objects
  3. Methods: Implementation of behavior
  4. Persistence: Long-term data storage
  5. Interfaces: Defined contracts
  6. Encapsulation: Grouping data and methods together
  7. Abstraction: Reducing complexity
  8. Polymorphism: Multiple implementations of an interface

Practical Examples

1. Attributes in Different Languages

// Java Attributes
public class Auto {
    // Instance attributes (per object)
    private String marke;           // Private property
    protected int baujahr;          // Protected property
    public double preis;            // Public property
    
    // Class attribute (shared by all instances)
    private static int anzahlAutos = 0;
    
    // Constant
    public static final int MAX_GESCHWINDIGKEIT = 250;
    
    // Constructor for initialization
    public Auto(String marke, int baujahr, double preis) {
        this.marke = marke;
        this.baujahr = baujahr;
        this.preis = preis;
        Auto.anzahlAutos++; // Increment class attribute
    }
    
    // Getter and setter for encapsulated attributes
    public String getMarke() {
        return marke;
    }
    
    public void setMarke(String marke) {
        this.marke = marke;
    }
    
    public static int getAnzahlAutos() {
        return anzahlAutos;
    }
}
// C# Attributes
public class Mitarbeiter
{
    // Auto-properties (modern syntax)
    public string Name { get; set; }
    public int Alter { get; private set; }  // Read-only from outside
    
    // Full property with validation
    private double gehalt;
    public double Gehalt
    {
        get { return gehalt; }
        set
        {
            if (value >= 0)
                gehalt = value;
            else
                throw new ArgumentException("Gehalt kann nicht negativ sein");
        }
    }
    
    // Static property
    public static string Firma { get; set; } = "TechCorp";
    
    // Constant
    public const decimal MINDESTGEHALT = 2000m;
    
    public Mitarbeiter(string name, int alter, double gehalt)
    {
        Name = name;
        Alter = alter;
        Gehalt = gehalt;
    }
}
# Python Attributes
class Person:
    # Class attribute
    anzahl_personen = 0
    
    def __init__(self, name, alter):
        # Instance attributes
        self.name = name          # Public
        self._alter = alter       # Protected (convention)
        self.__geheim = "data"    # Private (name mangling)
        
        Person.anzahl_personen += 1
    
    # Property for encapsulated access
    @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")
    
    # Static method
    @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 + "€");
    }
}

// Using 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. Implementing Persistence

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

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

4. Interfaces and APIs

// Programming interface
interface DatabaseInterface {
    // Abstract methods (no implementation)
    void connect() throws DatabaseException;
    void disconnect();
    boolean isConnected();
    
    // Query methods
    List<Map<String, Object>> query(String sql) throws DatabaseException;
    int execute(String sql) throws DatabaseException;
    
    // Default methods (since Java 8)
    default void connectWithTimeout(int timeout) throws DatabaseException {
        connect(); // Standard implementation
    }
}

// Custom exception class
class DatabaseException extends Exception {
    public DatabaseException(String message) {
        super(message);
    }
    
    public DatabaseException(String message, Throwable cause) {
        super(message, cause);
    }
}

// Concrete implementation
class MySQLDatabase implements DatabaseInterface {
    private boolean connected = false;
    private String connectionString;
    
    public MySQLDatabase(String connectionString) {
        this.connectionString = connectionString;
    }
    
    @Override
    public void connect() throws DatabaseException {
        try {
            // Simulated connection
            System.out.println("Connecting to MySQL: " + connectionString);
            Thread.sleep(1000); // Simulate network latency
            connected = true;
            System.out.println("Connection established");
        } catch (InterruptedException e) {
            throw new DatabaseException("Connection interrupted", e);
        }
    }
    
    @Override
    public void disconnect() {
        if (connected) {
            System.out.println("Connection closed");
            connected = false;
        }
    }
    
    @Override
    public boolean isConnected() {
        return connected;
    }
    
    @Override
    public List<Map<String, Object>> query(String sql) throws DatabaseException {
        if (!connected) {
            throw new DatabaseException("Not connected");
        }
        
        System.out.println("Executing: " + sql);
        
        // Simulated result
        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> row = new HashMap<>();
        row.put("id", 1);
        row.put("name", "Test data");
        result.add(row);
        
        return result;
    }
    
    @Override
    public int execute(String sql) throws DatabaseException {
        if (!connected) {
            throw new DatabaseException("Not connected");
        }
        
        System.out.println("Executing: " + sql);
        return 1; // Simulated affected rows
    }
}

// API usage
public class ApiDemo {
    public static void main(String[] args) {
        // Polymorphic use via interface
        DatabaseInterface db = new MySQLDatabase("jdbc:mysql://localhost/test");
        
        try {
            // Work through the interface
            db.connect();
            
            if (db.isConnected()) {
                List<Map<String, Object>> result = db.query("SELECT * FROM customers");
                System.out.println("Result: " + result.size() + " rows");
                
                int rows = db.execute("UPDATE customers SET status = 'active'");
                System.out.println("Affected rows: " + rows);
            }
            
        } catch (DatabaseException e) {
            System.err.println("Database error: " + e.getMessage());
        } finally {
            db.disconnect();
        }
    }
}

5. Web API Example

// REST API Controller (Spring Boot example)
@RestController
@RequestMapping("/api/customers")
public class CustomerAPI {
    
    private final CustomerService service;
    
    public CustomerAPI(CustomerService service) {
        this.service = service;
    }
    
    // GET /api/customers/{id}
    @GetMapping("/{id}")
    public ResponseEntity<Customer> getCustomer(@PathVariable Long id) {
        try {
            Customer customer = service.findCustomerById(id);
            return ResponseEntity.ok(customer);
        } catch (CustomerNotFoundException e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    // POST /api/customers
    @PostMapping
    public ResponseEntity<Customer> createCustomer(@RequestBody Customer customer) {
        Customer createdCustomer = service.createCustomer(customer);
        return ResponseEntity.status(HttpStatus.CREATED).body(createdCustomer);
    }
    
    // PUT /api/customers/{id}
    @PutMapping("/{id}")
    public ResponseEntity<Customer> updateCustomer(@PathVariable Long id, @RequestBody Customer customer) {
        try {
            Customer updatedCustomer = service.updateCustomer(id, customer);
            return ResponseEntity.ok(updatedCustomer);
        } catch (CustomerNotFoundException e) {
            return ResponseEntity.notFound().build();
        }
    }
    
    // DELETE /api/customers/{id}
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteCustomer(@PathVariable Long id) {
        service.deleteCustomer(id);
        return ResponseEntity.noContent().build();
    }
}

// Data model
class Customer {
    private Long id;
    private String name;
    private String email;
    private LocalDate birthDate;
    
    // Getters and setters
    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 getBirthDate() { return birthDate; }
    public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; }
}

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

OOP Concepts at a Glance

Encapsulation

// Data and methods bundled into a single unit
public class BankAccount {
    private double balance;  // Private data
    
    public void deposit(double amount) {  // Public method
        if (amount > 0) {
            balance += amount;
        }
    }
    
    public double getBalance() {
        return balance;
    }
}

Abstraction

// Complex reality simplified into essential features
abstract class Vehicle {
    protected String brand;
    
    public abstract void accelerate();
    public abstract void brake();
    
    public void display() {
        System.out.println("Vehicle: " + brand);
    }
}

Polymorphism

// Single interface, many implementations
interface Animal {
    void makeSound();
}

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Woof!");
    }
}

class Cat implements Animal {
    public void makeSound() {
        System.out.println("Meow!");
    }
}

// Usage
Animal animal1 = new Dog();
Animal animal2 = new Cat();

animal1.makeSound(); // Woof!
animal2.makeSound(); // Meow!

Persistence Strategies

Serialization

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

Database Persistence

  • Relational DB: Structured data with SQL
  • NoSQL DB: Flexible documents or key-value stores
  • 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 within the same program
  • Library APIs: Third-party libraries
  • Framework APIs: Spring, Django, React

Web APIs

  • REST: HTTP verbs, 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

Strengths and Weaknesses

Advantages of OOP Concepts

  • Organization: Clear code structure
  • Reusability: Components can be reused across projects
  • Maintainability: Modular design simplifies changes
  • Testability: Isolated components are easier to test
  • Scalability: Systems can grow without redesign

Disadvantages

  • Complexity: Overhead for small projects
  • Learning curve: Many concepts to master
  • Performance: Can be slower than procedural code
  • Over-engineering: Risk of unnecessary complexity

Common Exam Questions

  1. What’s the difference between an attribute and a method? Attributes represent data or properties, while methods represent behavior or functions of an object.

  2. Explain the concept of messaging in OOP! Messaging is how objects communicate with each other, typically implemented as method calls.

  3. What does persistence mean in programming? The ability to store data permanently so it remains available across program executions.

  4. What’s the purpose of interfaces? Interfaces define contracts between components, enabling loose coupling and polymorphism.

Key Resources

  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/

Continue Your OOP Learning Path

The next article in the OOP learning path covers OOP Encapsulation: Fundamentals, Information Hiding & Access Modifiers — how encapsulation shields internal state.

Back to Blog
Share:

Related Posts