Classes & OOP
Object-oriented programming
Introduction
In this lesson, you'll learn about classes & oop in Python. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Java, you're familiar with object-oriented programming.
Python has its own approach to object-oriented programming, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self, name: str):
self._name = name
@property
def name(self) -> str:
return self._name
@abstractmethod
def speak(self) -> str:
pass
class Dog(Animal):
def speak(self) -> str:
return f"{self.name} barks."
d = Dog("Rex")
print(d.speak())
print(isinstance(d, Animal))Comparing to Java
Here's how you might have written similar code in Java:
public abstract class Animal {
private String name;
public Animal(String name) { this.name = name; }
public String getName() { return name; }
public abstract String speak();
}
public class Dog extends Animal {
public Dog(String name) { super(name); }
@Override
public String speak() {
return getName() + " barks.";
}
}
Dog d = new Dog("Rex");
System.out.println(d.speak());
System.out.println(d instanceof Animal);You may be used to different syntax or behavior.
Python uses parentheses for inheritance; Java uses extends
You may be used to different syntax or behavior.
Python @abstractmethod replaces Java's abstract keyword
You may be used to different syntax or behavior.
Python @property replaces Java's getters/setters
You may be used to different syntax or behavior.
Python __init__ replaces Java constructors
Step-by-Step Breakdown
1. Inheritance Syntax
Python inherits via class Dog(Animal). super().__init__() calls the parent constructor.
class Dog extends Animal { public Dog(String n) { super(n); } }class Dog(Animal):
def __init__(self, name: str):
super().__init__(name)2. @property vs Getters
Python @property replaces Java's getMethod/setMethod pattern with clean attribute-style access.
public String getName() { return name; }@property
def name(self) -> str:
return self._name3. Abstract Methods
Python uses ABC (Abstract Base Class) and @abstractmethod decorator to enforce interface contracts.
public abstract String speak();@abstractmethod
def speak(self) -> str:
passCommon Mistakes
When coming from Java, developers often make these mistakes:
- Python uses parentheses for inheritance; Java uses extends
- Python @abstractmethod replaces Java's abstract keyword
- Python @property replaces Java's getters/setters
Key Takeaways
- extends → class Dog(Animal):
- Java getters → @property decorator
- abstract → ABC + @abstractmethod
- __init__ replaces Java constructor