📘 CodingMarble Learn

Object-Oriented Programming (OOP)

Object-oriented programming builds a program out of objects. A class is a blueprint that lists the data (attributes) and actions (methods) its objects will have. Each object is made from a class and keeps its own data. The four big ideas are encapsulation (hide data behind methods), inheritance (a new class reuses an old one), polymorphism (the same method call behaves in the right way for each object) and abstraction (show only what is needed).

🎬 Step-by-step story

  1. A class is a blueprint. Class Car says every car has a colour and a speed, and every car can accelerate.
  2. Objects are real things built from the class. Here are three car objects, each with its own colour.
  3. We call a method on one object: car1.accelerate(20). Only car1 changes. The others stay the same.
  4. Encapsulation keeps the data inside a shell. Outside code must use a method to change the speed.
  5. Inheritance: ElectricCar is made from Car. It gets everything Car has and adds a battery.
  6. Your turn: make objects, call accelerate() and describe(). Each kind of car answers in its own way.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

🤔 Common doubts, cleared

Is a class itself an object?

Think of the class as the plan only. Real data lives in objects made from it. (Advanced: Python also treats classes as objects, but for learning, class = plan.)

If two objects come from one class, do they share data?

No. Each object has its own copy of instance variables, like each car having its own colour.

Why did only car1 speed up?

A method acts on the object it is called on. self inside accelerate() meant car1.

Why not just change speed directly?

A method can check the value (no negative speed, no 999 km/h). Direct access skips those checks.

Does the child class copy the parent's code?

No, it reuses it. If Car gets a new method, ElectricCar gets it too.

What is the difference between overriding and overloading?

Overriding: a child replaces a parent method with the same signature. Overloading (Java): several methods with the same name but different parameters in one class.

Classes and objects

In procedural programming we write a list of steps and functions. In object-oriented programming (OOP) we group data and the code that works on it into objects.

class Car:
    def __init__(self, colour):
        self.colour = colour
        self.speed = 0

    def accelerate(self, amount):
        self.speed += amount

car1 = Car("red")
car2 = Car("yellow")
car1.accelerate(20)
print(car1.speed, car2.speed)   # 20 0

Constructors, self, and class vs instance variables

The constructor runs automatically when an object is made. In Python it is __init__; in Java it has the same name as the class. It gives the new object its starting values.

self (Python) or this (Java) means "this particular object". self.speed is the speed of the object the method was called on.

A method signature is the method name plus its parameter list, e.g. accelerate(amount). In Java: public void accelerate(int amount).

// Java
public class Car {
    private String colour;
    private int speed;
    public Car(String colour) { this.colour = colour; this.speed = 0; }
    public void accelerate(int amount) { speed += amount; }
}

Encapsulation and abstraction

Encapsulation means keeping an object's data inside it and letting the outside world change it only through methods. We make attributes private (Java private; Python name starting with __) and give getter and setter methods that can check values. For example, a bank account's withdraw() refuses to go below zero.

Abstraction means showing only what the user needs and hiding the details. You press a car's accelerator without knowing how the engine burns fuel. In code, a class gives simple methods and hides the complex parts. An abstract class or interface lists methods that child classes must provide.

Inheritance and polymorphism

Inheritance: a subclass (child) is built from a superclass (parent). It gets all the parent's attributes and methods and can add more. This is an "is-a" link: an ElectricCar is a Car.

Polymorphism ("many forms"): the same method name works differently for different classes. A child class can override a parent method with its own version.

class ElectricCar(Car):
    def __init__(self, colour):
        super().__init__(colour)
        self.battery = 100

    def describe(self):          # overrides Car.describe
        return "electric, battery " + str(self.battery)

for c in [Car("red"), ElectricCar("blue")]:
    print(c.describe())        # each answers in its own way

Designing with objects

A UML class diagram draws each class as a box with three parts: name, attributes, methods (+ public, − private). Composition/aggregation is a "has-a" link: a Car has an Engine. OOP makes code reusable, easier to test and easier for teams to share.

Try it

Pick something at home, like a mobile phone. Write its class: 3 attributes and 2 methods. Then write two objects with different values.

Key formulas and definitions

Worked examples

1. Write a class Student with name and marks, and a method is_pass() that returns True if marks ≥ 33.

class Student: def __init__(self, name, marks): self.name = name self.marks = marks def is_pass(self): return self.marks >= 33 s = Student("Asha", 72); s.is_pass() → True

2. car1 = Car("red"); car2 = car1; car2.accelerate(10). What is car1.speed?

10. car2 = car1 does not make a new object; both names point to the same object. Only Car(...) makes a new one.

3. Make a class variable that counts how many Car objects exist.

class Car: count = 0 def __init__(self, colour): self.colour = colour Car.count += 1 After Car("red") and Car("blue"), Car.count is 2.

4. Show encapsulation with a BankAccount that cannot go below zero.

class BankAccount: def __init__(self): self.__balance = 0 def deposit(self, x): if x > 0: self.__balance += x def withdraw(self, x): if x <= self.__balance: self.__balance -= x def get_balance(self): return self.__balance Outside code cannot write acc.__balance = -500.

5. Animal has speak() returning "...". Dog and Cat override it. What does the loop print? for a in [Dog(), Cat(), Animal()]: print(a.speak())

"Woof", "Meow", "...". Each object uses its own class's version: that is polymorphism.

6. Draw a UML box for class Book with private title and price and a public method apply_discount(p).

Book − title: str − price: float + apply_discount(p: float): void

Common mistakes

Practice quiz

1. A class is best described as:
2. In Python, the constructor method is named:
3. Hiding data and allowing access only through methods is:
4. class ElectricCar(Car) shows:
5. A child class giving its own version of a parent method is called:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What are the four pillars of OOP?

Encapsulation, abstraction, inheritance and polymorphism.

Which languages are object-oriented?

Python, Java, C++, C#, JavaScript and many more support OOP.

What is the difference between a class and an object?

A class is the blueprint; an object is one real instance made from it with its own data.

Where this is taught

Canada (Ontario)Grade 12A. Programming Concepts and Skills
Canada (Ontario)Grade 12B. Software Development
ItalySecondaria di secondo grado – classe 3ªTools and foundations
ItalySecondaria di secondo grado – classe 4ªTools and foundations
RomaniaClasa a IX-aStoring data and organising code in a programming language
RomaniaClasa a IX-aStoring data and organising code in a programming language
RomaniaClasa a IX-aStoring data and organising code in a programming language
RomaniaClasa a XI-aObject-oriented programming
RomaniaClasa a XII-aModule 3: Visual programming (optional)
Ukraine10 класProgramming language and data structures
England (GCSE, A level)Year 134.1 Fundamentals of programming (A-level)
USA (Common Core, NGSS, AP)Grade 9Algorithms and Programming
USA (Common Core, NGSS, AP)Grade 11Using Objects and Methods
USA (Common Core, NGSS, AP)Grade 11Class Creation
USA (Common Core, NGSS, AP)Grade 11Algorithms and Programming
South Korea고등학교 2학년Algorithms and programming
Germany (Bavaria)Jahrgangsstufe 9Object-oriented modelling and programming basics
Germany (Bavaria)Jahrgangsstufe 10Object-oriented modelling and programming
FranceTerminaleData structures

Learn first

Learn next

Related lessons

All Computer Science lessons