OOP Fundamentals: Class, Object, Instance, Attributes & Methods
This article is a concept explanation about the fundamentals of object-oriented programming – including class, object, attributes, and methods.
In a Nutshell
OOP is a programming paradigm that composes software from reusable, clearly structured “building blocks” – the objects. A class is the blueprint, an object is the concrete manifestation.
Compact Technical Description
Object-Oriented Programming (OOP) is a paradigm that models real-world objects through software objects. The fundamental difference between class and object is fundamental:
Class (Blueprint):
- Abstract template or pattern
- Defines attributes (properties) and methods (capabilities)
- Exists only once in the code
- Example: Class
Cardefines properties like color and methods likebrake()
Object/Instance (concrete thing):
- Concrete manifestation of a class
- Created at runtime (
newoperator) - Has specific attribute values
- Example: Object
myGolfwith color=“blue”, power=150HP
Core Concepts:
- Encapsulation: Data and methods are bundled into a unit
- Reusability: Classes can be instantiated multiple times
- Structure: Clear separation of responsibilities
- Abstraction: Complex reality reduced to relevant properties
Exam-Relevant Key Points
- Class vs Object: Abstract blueprint vs concrete instance
- Attributes: Properties/data of an object
- Methods: Behavior/capabilities of an object
- Instantiation: Creation of objects from classes
- Constructor: Special method for object creation
- Encapsulation: Data and methods bundled together
- IHK-relevant: Fundamental understanding for software development
- Practice: Reusability and maintainability of code
Core Components
- Class: Definition with attributes and methods
- Object: Concrete instance of a class
- Attributes: Properties/data of an object
- Methods: Behavior/functions of an object
- Constructor: Initialization method for new objects
- Instance variables: Object-specific data
- Class methods: Methods valid for the class
- Getter/Setter: Access methods for attributes
Practical Examples
1. Simple Class in Java
// Class as blueprint
public class Car {
// Attributes (properties)
private String color;
private int numberOfDoors;
private int powerInHP;
private int currentSpeed;
// Constructor for object creation
public Car(String color, int numberOfDoors, int powerInHP) {
this.color = color;
this.numberOfDoors = numberOfDoors;
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: " + numberOfDoors +
", Power: " + powerInHP + " HP" +
", Speed: " + currentSpeed + " km/h");
}
}
// Using the class
public class Garage {
public static void main(String[] args) {
// Objects (instances) created
Car myGolf = new Car("blue", 5, 150);
Car yourA3 = new Car("black", 3, 120);
Car companyCar = new Car("silver", 4, 200);
// Using objects
myGolf.display();
myGolf.accelerate(50);
myGolf.accelerate(30);
myGolf.brake(20);
System.out.println("---");
yourA3.display();
yourA3.accelerate(80);
System.out.println("---");
companyCar.display();
companyCar.accelerate(100);
}
}
2. Class in Python
# Class as blueprint
class Car:
# Class attribute (applies to all cars)
number_of_cars = 0
# Constructor
def __init__(self, color, number_of_doors, power_in_hp):
# Instance attributes (object-specific)
self.color = color
self.number_of_doors = number_of_doors
self.power_in_hp = power_in_hp
self.current_speed = 0
# Increase class attribute
Car.number_of_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.number_of_doors}, " +
f"Power: {self.power_in_hp} HP, " +
f"Speed: {self.current_speed} km/h")
# Class method
@classmethod
def get_number_of_cars(cls):
return cls.number_of_cars
# Using the class
def garage_demo():
# Objects (instances) created
my_golf = Car("blue", 5, 150)
your_a3 = Car("black", 3, 120)
company_car = Car("silver", 4, 200)
# Using 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_car.display()
company_car.accelerate(100)
print(f"Number of created cars: {Car.get_number_of_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 numberOfDoors;
private int powerInHP;
private int currentSpeed;
// Static property for all cars
public static int NumberOfCars { get; private set; }
// Constructor
public Car(string color, int numberOfDoors, int powerInHP)
{
this.color = color;
this.numberOfDoors = numberOfDoors;
this.powerInHP = powerInHP;
this.currentSpeed = 0;
NumberOfCars++;
}
// 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: {numberOfDoors}, " +
$"Power: {powerInHP} HP, " +
$"Speed: {currentSpeed} km/h");
}
}
// Using the class
public class Garage
{
public static void Main(string[] args)
{
// Objects (instances) created
Car myGolf = new Car("blue", 5, 150);
Car yourA3 = new Car("black", 3, 120);
Car companyCar = new Car("silver", 4, 200);
// Using objects
myGolf.Display();
myGolf.Accelerate(50);
myGolf.Accelerate(30);
myGolf.Brake(20);
Console.WriteLine("---");
yourA3.Display();
yourA3.Accelerate(80);
Console.WriteLine("---");
companyCar.Display();
companyCar.Accelerate(100);
Console.WriteLine($"Number of created cars: {Car.NumberOfCars}");
}
}
Concepts in Detail
Constructors
// Overloaded constructors in Java
public class Car {
private String color;
private int power;
// Default constructor
public Car() {
this.color = "black";
this.power = 100;
}
// Constructor with parameters
public Car(String color, int power) {
this.color = color;
this.power = power;
}
// Copy constructor
public Car(Car other) {
this.color = other.color;
this.power = other.power;
}
}
Static vs Instance Members
public class MathUtil {
// Static method - belongs to class
public static int add(int a, int b) {
return a + b;
}
// Instance method - belongs to object
private int value;
public MathUtil(int startValue) {
this.value = startValue;
}
public int addToValue(int a) {
this.value += a;
return this.value;
}
}
// Usage
int result1 = MathUtil.add(5, 3); // Static
MathUtil calculator = new MathUtil(10);
int result2 = calculator.addToValue(5); // Instance
Getters and Setters
public class Person {
private String name;
private int age;
// Getter
public String getName() {
return name;
}
// Setter with validation
public void setAge(int age) {
if (age >= 0 && age <= 150) {
this.age = age;
} else {
throw new IllegalArgumentException("Invalid age");
}
}
// Getter for calculated value
public boolean isAdult() {
return age >= 18;
}
}
Advantages and Disadvantages
Advantages of OOP
- Reusability: Classes can be used multiple times
- Maintainability: Clear structure facilitates changes
- Understandability: Real world is modeled
- Encapsulation: Data is protected and controllably accessible
- Scalability: Large systems can be structured
Disadvantages
- Overhead: More code for simple tasks
- Learning curve: Object-oriented thinking requires practice
- Performance: Object creation can be expensive
- Complexity: Can become unclear with too many classes
Common Exam Questions
-
What is the difference between class and object? Class is the blueprint, object is the concrete instance at runtime.
-
Explain the terms attribute and method! Attributes are properties/data, methods are behavior/functions of an object.
-
What is a constructor? Special method for initializing new objects, called on
new. -
Why is encapsulation important? Protects data from uncontrolled access and enables validation.
Most Important Sources
- https://en.wikipedia.org/wiki/Object-oriented_programming
- https://docs.oracle.com/javase/tutorial/java/concepts/
- https://docs.python.org/3/tutorial/classes.html
Recommended Literature: Object-Oriented Programming
Keine Bücher für Kategorie "objektorientierte-programmierung" gefunden.