Skip to content
IRC-CodingIRC-Coding
OOP BasicsClass ObjectAttributes MethodsInstanceConstructor

OOP Basics: Classes, Objects, Instances & Methods

Learn OOP fundamentals: classes as blueprints, objects as instances, attributes, methods, constructors, and their relationships.

S

schutzgeist

6 min read
OOP Basics: Classes, Objects, Instances & Methods

OOP Fundamentals: Classes, Objects, Instances, Attributes & Methods

This article explains the core concepts of object-oriented programming – covering classes, objects, attributes, and methods.

In a Nutshell

OOP is a programming paradigm that builds software from reusable, well-structured “building blocks” – objects. A class is the blueprint; an object is the concrete instance.

Core Concepts

Object-Oriented Programming (OOP) is a paradigm that models real-world objects through software objects. The fundamental distinction between a class and an object is crucial:

Class (Blueprint):

  • Abstract template or schema
  • Defines attributes (properties) and methods (capabilities)
  • Exists once in your code
  • Example: Class Car defines properties like color and methods like brake()

Object/Instance (concrete thing):

  • Concrete manifestation of a class
  • Created at runtime using the new operator
  • Has specific attribute values
  • Example: Object myGolf with color=“blue”, power=150hp

Key Principles:

  • Encapsulation: Data and methods bundled into a single unit
  • Reusability: Classes can be instantiated multiple times
  • Organization: Clear separation of responsibilities
  • Abstraction: Complex reality reduced to relevant properties

Exam-Ready Key Points

  • Class vs Object: Abstract blueprint vs concrete instance
  • Attributes: Properties and data of an object
  • Methods: Behavior and capabilities of an object
  • Instantiation: Creating objects from classes
  • Constructor: Special method that initializes new objects
  • Encapsulation: Grouping data and methods together
  • Professional Context: Essential knowledge for software development
  • Practice: Code reuse and maintainability

Core Components

  1. Class: Definition containing attributes and methods
  2. Object: Concrete instance of a class
  3. Attributes: Properties and data of an object
  4. Methods: Behavior and functions of an object
  5. Constructor: Initialization method for new objects
  6. Instance Variables: Object-specific data
  7. Class Methods: Methods valid for the class itself
  8. Getters/Setters: Access methods for attributes

Practical Examples

1. Simple Class in Java

// Class as blueprint
public class Car {
    // Attributes (properties)
    private String color;
    private int numDoors;
    private int powerInHP;
    private int currentSpeed;
    
    // Constructor for object creation
    public Car(String color, int numDoors, int powerInHP) {
        this.color = color;
        this.numDoors = numDoors;
        this.powerInHP = powerInHP;
        this.currentSpeed = 0;
    }
    
    // Methods (behavior)
    public void accelerate(int kmh) {
        this.currentSpeed += kmh;
        System.out.println("Car accelerates to " + this.currentSpeed + " km/h");
    }
    
    public void brake(int kmh) {
        if (this.currentSpeed >= kmh) {
            this.currentSpeed -= kmh;
            System.out.println("Car brakes to " + this.currentSpeed + " km/h");
        } else {
            System.out.println("Cannot brake below 0 km/h");
        }
    }
    
    // Getter methods for accessing attributes
    public String getColor() {
        return color;
    }
    
    public int getCurrentSpeed() {
        return currentSpeed;
    }
    
    public void display() {
        System.out.println("Car - Color: " + color + 
                          ", Doors: " + numDoors + 
                          ", Power: " + powerInHP + " hp" +
                          ", Speed: " + currentSpeed + " km/h");
    }
}

// Using the class
public class Garage {
    public static void main(String[] args) {
        // Create objects (instances)
        Car myGolf = new Car("blue", 5, 150);
        Car yourA3 = new Car("black", 3, 120);
        Car companyAuto = new Car("silver", 4, 200);
        
        // Use objects
        myGolf.display();
        myGolf.accelerate(50);
        myGolf.accelerate(30);
        myGolf.brake(20);
        
        System.out.println("---");
        
        yourA3.display();
        yourA3.accelerate(80);
        
        System.out.println("---");
        
        companyAuto.display();
        companyAuto.accelerate(100);
    }
}

2. Class in Python

# Class as blueprint
class Car:
    # Class attribute (valid for all cars)
    num_cars = 0
    
    # Constructor
    def __init__(self, color, num_doors, power_in_hp):
        # Instance attributes (object-specific)
        self.color = color
        self.num_doors = num_doors
        self.power_in_hp = power_in_hp
        self.current_speed = 0
        
        # Increment class attribute
        Car.num_cars += 1
    
    # Methods
    def accelerate(self, kmh):
        self.current_speed += kmh
        print(f"Car accelerates to {self.current_speed} km/h")
    
    def brake(self, kmh):
        if self.current_speed >= kmh:
            self.current_speed -= kmh
            print(f"Car brakes to {self.current_speed} km/h")
        else:
            print("Cannot brake below 0 km/h")
    
    def display(self):
        print(f"Car - Color: {self.color}, Doors: {self.num_doors}, " +
              f"Power: {self.power_in_hp} hp, " +
              f"Speed: {self.current_speed} km/h")
    
    # Class method
    @classmethod
    def get_num_cars(cls):
        return cls.num_cars

# Using the class
def garage_demo():
    # Create objects (instances)
    my_golf = Car("blue", 5, 150)
    your_a3 = Car("black", 3, 120)
    company_auto = Car("silver", 4, 200)
    
    # Use objects
    my_golf.display()
    my_golf.accelerate(50)
    my_golf.accelerate(30)
    my_golf.brake(20)
    
    print("---")
    
    your_a3.display()
    your_a3.accelerate(80)
    
    print("---")
    
    company_auto.display()
    company_auto.accelerate(100)
    
    print(f"Number of cars created: {Car.get_num_cars()}")

if __name__ == "__main__":
    garage_demo()

3. Class in C#

using System;

// Class as blueprint
public class Car
{
    // Attributes (properties)
    private string color;
    private int numDoors;
    private int powerInHP;
    private int currentSpeed;
    
    // Static property for all cars
    public static int NumCars { get; private set; }
    
    // Constructor
    public Car(string color, int numDoors, int powerInHP)
    {
        this.color = color;
        this.numDoors = numDoors;
        this.powerInHP = powerInHP;
        this.currentSpeed = 0;
        NumCars++;
    }
    
    // Methods
    public void Accelerate(int kmh)
    {
        this.currentSpeed += kmh;
        Console.WriteLine($"Car accelerates to {this.currentSpeed} km/h");
    }
    
    public void Brake(int kmh)
    {
        if (this.currentSpeed >= kmh)
        {
            this.currentSpeed -= kmh;
            Console.WriteLine($"Car brakes to {this.currentSpeed} km/h");
        }
        else
        {
            Console.WriteLine("Cannot brake below 0 km/h");
        }
    }
    
    // Properties for accessing attributes
    public string Color => color;
    public int CurrentSpeed => currentSpeed;
    
    public void Display()
    {
        Console.WriteLine($"Car - Color: {color}, Doors: {numDoors}, " +
                         $"Power: {powerInHP} hp, " +
                         $"Speed: {currentSpeed} km/h");
    }
}

// Using the class
public class Garage
{
    public static void Main(string[] args)
    {
        // Create objects (instances)
        Car myGolf = new Car("blue", 5, 150);
        Car yourA3 = new Car("black", 3, 120);
        Car companyAuto = new Car("silver", 4, 200);
        
        // Use objects
        myGolf.Display();
        myGolf.Accelerate(50);
        myGolf.Accelerate(30);
        myGolf.Brake(20);
        
        Console.WriteLine("---");
        
        yourA3.Display();
        yourA3.Accelerate(80);
        
        Console.WriteLine("---");
        
        companyAuto.Display();
        companyAuto.Accelerate(100);
        
        Console.WriteLine($"Number of cars created: {Car.NumCars}");
    }
}

Concepts in Detail

Constructors

// Overloaded constructors in Java
public class Auto {
    private String farbe;
    private int leistung;
    
    // Default constructor
    public Auto() {
        this.farbe = "schwarz";
        this.leistung = 100;
    }
    
    // Constructor with parameters
    public Auto(String farbe, int leistung) {
        this.farbe = farbe;
        this.leistung = leistung;
    }
    
    // Copy constructor
    public Auto(Auto other) {
        this.farbe = other.farbe;
        this.leistung = other.leistung;
    }
}

Static vs Instance Members

public class MathUtil {
    // Static method - belongs to the class
    public static int addiere(int a, int b) {
        return a + b;
    }
    
    // Instance method - belongs to the object
    private int wert;
    
    public MathUtil(int startWert) {
        this.wert = startWert;
    }
    
    public int addiereZuWert(int a) {
        this.wert += a;
        return this.wert;
    }
}

// Usage
int ergebnis1 = MathUtil.addiere(5, 3);  // Static
MathUtil rechner = new MathUtil(10);
int ergebnis2 = rechner.addiereZuWert(5);  // Instance

Getters and Setters

public class Person {
    private String name;
    private int alter;
    
    // Getter
    public String getName() {
        return name;
    }
    
    // Setter with validation
    public void setAlter(int alter) {
        if (alter >= 0 && alter <= 150) {
            this.alter = alter;
        } else {
            throw new IllegalArgumentException("Ungültiges Alter");
        }
    }
    
    // Getter for computed value
    public boolean istVolljaehrig() {
        return alter >= 18;
    }
}

Advantages and Disadvantages

Advantages of OOP

  • Reusability: Classes can be used multiple times across projects
  • Maintainability: Clear structure makes code easier to update
  • Understandability: Models the real world intuitively
  • Encapsulation: Data is protected and accessed in a controlled way
  • Scalability: Large systems can be organized in a structured manner

Disadvantages

  • Overhead: More code needed for simple tasks
  • Learning curve: Object-oriented thinking requires practice
  • Performance: Creating objects can be costly
  • Complexity: Too many classes make code hard to navigate

Common Exam Questions

  1. What’s the difference between a class and an object? A class is the blueprint; an object is the concrete instance at runtime.

  2. Explain the terms attribute and method! Attributes are properties or data; methods are the behavior or functions of an object.

  3. What is a constructor? A special method that initializes new objects, invoked when using new.

  4. Why is encapsulation important? It protects data from uncontrolled access and enables validation.

Key Resources

  1. https://de.wikipedia.org/wiki/Objektorientierte_Programmierung
  2. https://docs.oracle.com/javase/tutorial/java/concepts/
  3. https://docs.python.org/3/tutorial/classes.html

Continue Your OOP Learning Path

The next article in the OOP learning path covers OOP Concepts: Attributes, Messages, Method Calls, Persistence & Interfaces — essential OOP terminology explained.

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

Back to Blog
Share:

Related Posts