Zum Inhalt springen

English:Object-Oriented Programming Basics

Aus MOOCsWiki Staging
Version vom 27. August 2026, 14:16 Uhr von Glanz (Diskussion | Beiträge) (aiMOOC über GPT aiMOOC Action erstellt)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
aiMOOC-Siegel

Object-Oriented Programming Basics



Introduction

Object-oriented programming, often shortened to OOP, is a way of organizing a program around objects. An object combines data with the actions that can use or change that data. OOP is used in many programming languages, including Python, Java, C Sharp, and C++.

In this course, you will learn the basic ideas of OOP by modeling familiar things such as game characters, library books, and robots. The examples use Python-like code because its syntax is readable, but the main ideas transfer to many other languages.

The image above visualizes a programming object as a combination of attributes and methods. That combination is central to OOP.


Learning Goals

By the end of the course, you should be able to explain the difference between a class and an object, identify attributes and methods, create simple classes and objects, use constructors to initialize objects, describe encapsulation, inheritance, abstraction, and polymorphism, read a basic UML class diagram, and decide when an object-oriented design is useful.


Why Organize Programs with Objects?

A small program can store information in separate variables and use separate functions. As a program grows, however, it becomes harder to remember which variables belong together and which functions are allowed to change them. OOP helps group related information and behavior.

Imagine a simple school game with several characters. Each character might have a name, a health value, and a position. Each character might also move, take damage, or speak. Instead of managing many unrelated variables, you can represent each character as one object.

This idea is called modeling. You decide which parts of the real situation matter for your program and represent only those parts. A game character does not need every property of a real person. It only needs the data and behavior required by the game.


Class and Object

A class is a blueprint or definition. It describes what data and behavior a type of object should have. An object is one particular instance created from that class.

For example, a class called Robot might describe that every robot has a name and an energy level. The objects Nova and Pixel can both be created from the Robot class, but each object can have its own values.

A useful comparison is a cookie cutter and cookies. The cutter represents the class: it describes a shape. Each cookie represents an object: it is a separate instance created according to that shape. The comparison is not perfect, because software objects also have behavior, but it helps distinguish a definition from an instance.


Attributes and Methods

An attribute stores information about an object. Attributes describe its current state. A robot object could have attributes such as name, energy, and x_position.

A method is a function that belongs to a class and describes something its objects can do. A robot might have methods such as move, charge, and report_status.

You can think of attributes as answers to questions such as “What does this object know about itself?” and methods as answers to “What can this object do?”


Building Your First Class

The following Python example defines a small Robot class.

class Robot:
    def __init__(self, name, energy):
        self.name = name
        self.energy = energy

    def report_status(self):
        return f"{self.name} has {self.energy} energy points."

nova = Robot("Nova", 80)
pixel = Robot("Pixel", 55)

print(nova.report_status())
print(pixel.report_status())

The line beginning with class creates the class definition. The lines nova = Robot(...) and pixel = Robot(...) create two separate objects. Each object has its own attribute values, even though both objects follow the same class definition.


Constructors and self

A constructor is special code used when a new object is created. In Python, the method named __init__ is commonly used to initialize a new instance after it is created.

The parameter self refers to the current object inside an instance method. In self.name = name, the value received through the parameter name is stored in the name attribute of that particular object.

This matters because two Robot objects can hold different values at the same time. Changing nova.energy does not automatically change pixel.energy.


Changing State with Methods

Methods often change an object's state. Here is an expanded version.

class Robot:
    def __init__(self, name, energy):
        self.name = name
        self.energy = energy

    def move(self, steps):
        cost = steps * 2
        if cost <= self.energy:
            self.energy -= cost
            return f"{self.name} moved {steps} steps."
        return f"{self.name} does not have enough energy."

nova = Robot("Nova", 20)
print(nova.move(4))
print(nova.energy)

The move method checks the object's energy before changing it. This is more controlled than allowing every part of a program to change the energy value in any way it wants.


Encapsulation and Abstraction

Encapsulation means keeping related data and behavior together and controlling how an object's internal state is accessed or changed. The purpose is not simply to hide everything. It is to create a clear boundary around an object's responsibilities.

For example, a BankAccount class might provide deposit and withdraw methods instead of allowing any part of the program to set the balance to any value. The methods can check rules before changing the balance.

This educational diagram invites you to think about a machine from the outside. You can use its allowed controls without needing to know every internal detail. That leads to a related idea: abstraction.

Abstraction means showing the important features of something while leaving unnecessary internal detail out of the way. When you call a method such as robot.move(3), you use a simple interface. You do not need to think about every line inside the method each time you call it.


Public Interfaces and Internal Details

A class's public interface is the set of operations that other parts of the program are expected to use. A good interface makes valid actions easy and invalid actions harder.

Different OOP languages enforce access rules differently. Java and C++ have explicit access modifiers such as public and private. Python relies more on naming conventions and properties, although it also has mechanisms that discourage direct access to some names. The general design idea is the same: decide which parts of an object should be used from outside and which parts are implementation details.


Inheritance

Inheritance allows one class to build on another class. The more general class is often called a base class, parent class, or superclass. A more specific class that inherits from it is often called a subclass or child class.

Suppose a game has different kinds of characters. All characters have a name and health, but a Wizard also has magic points. You can model the shared parts once and extend them.

class Character:
    def __init__(self, name, health):
        self.name = name
        self.health = health

    def describe(self):
        return f"{self.name} has {self.health} health."

class Wizard(Character):
    def __init__(self, name, health, magic):
        super().__init__(name, health)
        self.magic = magic

    def cast_spell(self):
        return f"{self.name} casts a spell."

merlin = Wizard("Merlin", 90, 60)
print(merlin.describe())
print(merlin.cast_spell())

The Wizard class inherits the name, health, and describe behavior from Character, then adds magic and cast_spell.

Inheritance can reduce repetition when the relationship truly means “is a kind of.” However, inheritance should not be used only because two classes happen to share a few lines of code. Sometimes composition is a better design.


Composition: Has-a Relationships

Composition means building an object by giving it other objects as parts. A Car has an Engine, so composition is usually a more natural model than saying a Car is an Engine.

class Engine:
    def start(self):
        return "Engine started."

class Car:
    def __init__(self):
        self.engine = Engine()

    def start(self):
        return self.engine.start()

A useful design question is: “Is this object a special kind of the other object, or does it contain or use the other object?” The first can suggest inheritance; the second can suggest composition.


Polymorphism

Polymorphism means that different kinds of objects can respond to the same operation in their own way. The word comes from roots meaning “many forms.”

Consider two classes that both provide a speak method.

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

animals = [Dog(), Cat()]

for animal in animals:
    print(animal.speak())

The loop calls the same method name, speak, on each object. The result depends on the actual object. This lets programs work with a common interface without needing a separate instruction for every possible class.

Polymorphism can appear in several forms depending on the language. At this level, the most important idea is that code can send the same kind of message or method call to different objects and receive behavior appropriate to each object.


Reading a UML Class Diagram

UML is a visual language used to model software systems. A basic UML class diagram often shows a class as a box with compartments.

The top compartment contains the class name. The middle compartment usually lists attributes. The bottom compartment usually lists operations or methods. Lines and arrows can show relationships such as inheritance, association, or composition.

You do not need to memorize every UML symbol to benefit from class diagrams. For Grades 9–10, focus first on identifying classes, important attributes, important methods, and clear relationships.


From a Problem to a Class Model

Suppose you are designing a school library app. A useful first model might include Book, Member, and Loan.

A Book might store a title, author, and availability state. A Member might store a name and member identifier. A Loan might connect one Book to one Member for a period of time. Methods could include borrow, return_book, and is_overdue.

Before writing code, ask three questions: What objects exist in the problem? What information must each object remember? What actions should each object be responsible for? These questions help turn a real situation into a software model.


A Complete Mini-Project: Digital Pet

This example combines several OOP ideas in one small program.

class DigitalPet:
    def __init__(self, name):
        self.name = name
        self._hunger = 5

    def feed(self):
        self._hunger = max(0, self._hunger - 2)
        return f"{self.name} has been fed."

    def status(self):
        return f"{self.name} has hunger level {self._hunger}."

class FlyingPet(DigitalPet):
    def fly(self):
        return f"{self.name} flies through the air."

pets = [DigitalPet("Milo"), FlyingPet("Sky")]

for pet in pets:
    print(pet.status())

The class DigitalPet defines shared data and behavior. Each instance has its own name and hunger state. The feed method controls how hunger changes, which illustrates encapsulation. FlyingPet inherits from DigitalPet and adds new behavior. A collection can store objects from related classes and treat them through shared methods.


Common Mistakes and Debugging

A common beginner mistake is confusing a class with an object. Remember that the class is the definition, while an object is one instance.

Another mistake is forgetting that each object has its own state. If two objects unexpectedly affect each other, check whether you accidentally used shared class data when you intended separate instance data.

A third mistake is creating a class for every noun in a problem. Good modeling is selective. Create classes when they help group meaningful data and behavior.

Inheritance can also be overused. If the relationship does not clearly mean “is a kind of,” consider composition. Good OOP is not about using the largest number of classes. It is about making responsibilities and relationships understandable.

When debugging, inspect one object at a time. Check the values of its attributes before and after a method call. Trace which method runs. Test small examples before combining many objects.


OOP and Other Programming Styles

OOP is one programming paradigm, not the only one. Procedural programming organizes a program mainly around procedures or functions and sequences of steps. Functional programming emphasizes functions, expressions, and controlled data transformation. Real programs often combine ideas from more than one paradigm.

OOP is especially useful when a problem contains entities with state and behavior that interact over time. A graphical game, simulation, school management system, or user interface can often be modeled naturally with objects. For a tiny calculation, OOP may add unnecessary complexity.

The goal is not to decide that OOP is always best. The goal is to understand its tools well enough to choose them when they improve a program's structure.


Interactive Tasks


Quiz: Test Your Knowledge

What is a class in object-oriented programming? (A blueprint that defines data and behavior for objects) (!A single value stored in a variable) (!A loop that repeats instructions) (!A file containing only pictures)




What is an object? (An instance created from a class) (!A comment that explains code) (!A programming language) (!A rule that stops all methods)




What does an attribute usually represent? (Data or state belonging to an object) (!A video embedded in a page) (!A mistake in program syntax) (!A command that ends every program)




What is a method? (A function associated with a class or object) (!A picture of a class diagram) (!A number that cannot change) (!A name for every programming language)




What is a main purpose of encapsulation? (To control access to related data and behavior) (!To remove every class from a program) (!To make every attribute global) (!To replace methods with comments)




What does inheritance allow a subclass to do? (Build on data and behavior defined by a more general class) (!Erase all methods from its parent) (!Turn every object into a string) (!Prevent objects from storing state)




What does polymorphism allow? (Different objects to respond to the same operation in their own way) (!Only one object to exist in a program) (!Every class to have exactly one method) (!All attributes to store identical values)




Which relationship is best described by composition? (A car has an engine) (!A wizard is a character) (!A cat is an animal) (!A square is a shape)




What does a UML class diagram help you represent? (Classes attributes methods and relationships) (!Only the colors used in an interface) (!Only the order of keyboard keys) (!The speed of a computer processor)




When is object-oriented design especially useful? (When a problem has interacting entities with state and behavior) (!Whenever a program contains only one calculation) (!Only when no functions are allowed) (!Only when the program has no data)





Memory Game

Class Blueprint that defines a type of object
Object Individual instance created from a blueprint
Attribute Stored state belonging to an instance
Method Behavior that an instance can perform
Constructor Setup code used when creating an instance
Abstraction Focus on essential features while hiding unnecessary detail





Drag and Drop

Match the correct terms. Topic
Class blueprint Defines shared attributes and methods
Object instance Stores its own current state
Encapsulation boundary Controls how internal data is accessed
Inheritance relationship Connects a specialized class to a more general class
Polymorphic method call Produces behavior based on the actual object




Match each OOP idea with the explanation that best describes it.


Crossword Puzzle

Encapsulation Which principle controls access to an object's internal state?
Inheritance Which principle lets a specialized class build on a general class?
Polymorphism Which principle allows one operation to have different object-specific behavior?
Constructor What initializes a new object's starting state?
Attribute What stores a piece of state inside an object?
Method What do you call a behavior defined by a class?





LearningApps


Cloze Text

Complete the text.

A

is a blueprint that defines data and behavior for a type of object. An

is one instance created from that blueprint. Information stored in an object is often called an

. A function that belongs to a class is called a

. A constructor helps establish an object's initial

.

creates a boundary around related data and behavior.

lets a specialized class build on a more general class.

allows different objects to respond to the same operation in their own way. A simple

class diagram can show classes, attributes, methods, and relationships.




Open-Ended Tasks


Easy

  1. Class Hunt: Find five everyday examples that could be modeled as classes, and for each one write two possible attributes and two possible methods.
  2. Object Cards: Create paper or digital cards for three objects from the same class and give each object different attribute values.
  3. Robot Class: Write or sketch a simple Robot class with a name, an energy attribute, and two methods, then explain what each part does.
  4. UML Sketch: Draw a one-class UML diagram for a Book, including at least three attributes and three methods.


Standard

  1. Digital Pet Project: Build a small DigitalPet program with a constructor, at least three attributes, and methods that safely change the pet's state.
  2. Interview a Programmer: Interview a programmer, computing teacher, or advanced student about where they use classes and objects, then summarize the most useful example in your own words.
  3. Inheritance Design: Design a superclass and at least two subclasses for a game, school, or transport system, and explain why each subclass has an is-a relationship with the superclass.
  4. OOP Explainer Video: Produce a two-to-four-minute video that teaches class, object, attribute, and method using one clear real-world analogy and one code example.


Advanced

  1. Library Model: Design a small library system with at least four interacting classes, justify the responsibilities of each class, and show the relationships in a UML diagram.
  2. Composition Investigation: Compare an inheritance-based and composition-based design for the same feature, implement or diagram both, and argue which design is easier to extend.
  3. Polymorphism Experiment: Create at least three classes that respond differently to the same method call, run a test collection of their objects, and explain why the calling code does not need separate instructions for every class.
  4. Refactor a Program: Find or write a short procedural program, redesign it with classes where appropriate, test both versions, and evaluate whether the object-oriented version improves clarity or creates unnecessary complexity.



Learning Assessment

  1. Modeling Challenge: Given a description of a school event app, identify suitable classes, attributes, methods, and relationships, then justify why each belongs in your model.
  2. Code Reasoning: Examine a short program with two objects from the same class, predict the state of each object after several method calls, and explain your reasoning step by step.
  3. Encapsulation Review: Redesign a class whose data can be changed to invalid values from anywhere in the program, then explain how your public methods protect the object's valid state.
  4. Inheritance or Composition: For three proposed class relationships, decide whether inheritance, composition, or neither is most suitable and defend each choice using is-a and has-a reasoning.
  5. Polymorphism Transfer: Design a new example in which unrelated or related objects share a common method name, and explain how polymorphism could simplify the code that uses those objects.
  6. Design Evaluation: Compare an object-oriented solution and a procedural solution to the same small problem, using criteria such as readability, reuse, testability, and unnecessary complexity.




Evidence of Learning

Strong evidence of learning includes accurate explanations of class, object, attribute, method, constructor, encapsulation, abstraction, inheritance, composition, and polymorphism; correct creation of multiple objects with independent state; working methods that read or change state predictably; sensible use of a constructor; a UML diagram that matches the intended program structure; code or pseudocode that demonstrates at least one relationship between classes; test cases that show expected and unexpected inputs; explanations of design choices rather than only finished code; a project product such as a digital pet, game model, library model, diagram, interview summary, or explainer video; and the ability to transfer OOP ideas to a new problem and judge whether OOP is appropriate.




OERs on the Topic

The English Wikipedia article on Object-oriented programming provides a broader reference for the paradigm, its terminology, history, and related concepts. You can also explore Class (computer programming), Object (computer science), Encapsulation (computer programming), Inheritance (object-oriented programming), Polymorphism (computer science), and Unified Modeling Language as follow-up topics.



Linked Learning Areas


aiMOOC Projects

MOOCwiki · Deutsch

Nach dem Lernen ist vor dem Lernen

Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.

Zur MOOCwiki-Hauptseite

Mediathek

Mediathek

Inhalte werden geladen ...

Mediathek wird aus dem Wiki geladen ...