oop-inheritance-composition
БесплатноБез исполняемых скриптовНе проверенUse when deciding between inheritance and composition in object-oriented design. Use when creating class hierarchies or composing objects from smaller…
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
OOP Inheritance and Composition
Master inheritance and composition to build flexible, maintainable object-oriented systems. This skill focuses on understanding when to use inheritance versus composition and how to apply each effectively.
Inheritance Fundamentals
Basic Inheritance in Java
// Base class with common behavior
public abstract class Vehicle {
private String brand;
private String model;
private int year;
protected double currentSpeed;
protected Vehicle(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
this.currentSpeed = 0.0;
}
// Template method pattern
public final void start() {
performSafetyCheck();
startEngine();
System.out.println(brand + " " + model + " started");
}
// Hook method for subclasses
protected void performSafetyCheck() {
System.out.println("Performing basic safety check");
}
// Abstract method - must be implemented
protected abstract void startEngine();
public void accelerate(double speed) {
currentSpeed += speed;
System.out.println("Current speed: " + currentSpeed);
}
public void brake(double reduction) {
currentSpeed = Math.max(0, currentSpeed - reduction);
System.out.println("Current speed: " + currentSpeed);
}
// Getters
public String getBrand() { return brand; }
public String getModel() { return model; }
public int getYear() { return year; }
public double getCurrentSpeed() { return currentSpeed; }
}
// Concrete implementation
public class Car extends Vehicle {
private int numberOfDoors;
private boolean isSunroofOpen;
public Car(String brand, String model, int year, int numberOfDoors) {
super(brand, model, year);
this.numberOfDoors = numberOfDoors;
this.isSunroofOpen = false;
}
@Override
protected void startEngine() {
System.out.println("Car engine started with ignition");
}
@Override
protected void performSafetyCheck() {
super.performSafetyCheck();
System.out.println("Checking doors are closed");
System.out.println("Checking seatbelts");
}
public void openSunroof() {
if (currentSpeed == 0) {
isSunroofOpen = true;
System.out.println("Sunroof opened");
} else {
System.out.println("Stop the car before opening sunroof");
}
}
public int getNumberOfDoors() {
return numberOfDoors;
}
}
// Another concrete implementation
public class Motorcycle extends Vehicle {
private boolean hasWindshield;
public Motorcycle(String brand, String model, int year, boolean hasWindshield) {
super(brand, model, year);
this.hasWindshield = hasWindshield;
}
@Override
protected void startEngine() {
System.out.println("Motorcycle engine started with kick/button");
}
@Override
public void accelerate(double speed) {
// Override to add motorcycle-specific behavior
if (currentSpeed + speed > 200) {
System.out.println("Warning: Maximum safe speed exceeded!");
}
super.accelerate(speed);
}
public boolean hasWindshield() {
return hasWindshield;
}
}
Inheritance in Python
from abc import ABC, abstractmethod
from typing import List, Optional
from datetime import datetime
class Employee(ABC):
"""Abstract base class for all employees."""
def __init__(self, employee_id: str, name: str, email: str, hire_date: datetime):
self._employee_id = employee_id
self._name = name
self._email = email
self._hire_date = hire_date
self._is_active = True
@property
def employee_id(self) -> str:
return self._employee_id
@property
def name(self) -> str:
return self._name
@property
def email(self) -> str:
return self._email
@property
def hire_date(self) -> datetime:
return self._hire_date
@property
def years_of_service(self) -> int:
return (datetime.now() - self._hire_date).days // 365
# Template method
def process_payroll(self) -> float:
"""Process payroll - template method."""
if not self._is_active:
raise ValueError("Cannot process payroll for inactive employee")
base_pay = self.calculate_pay()
bonus = self.calculate_bonus()
deductions = self.calculate_deductions()
total_pay = base_pay + bonus - deductions
self.record_payment(total_pay)
return total_pay
# Abstract methods - must be implemented by subclasses
@abstractmethod
def calculate_pay(self) -> float:
"""Calculate base pay."""
pass
# Hook methods with default implementation
def calculate_bonus(self) -> float:
"""Calculate bonus - can be
Установить oop-inheritance-composition в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
BashReadFAQ
Что делает скилл oop-inheritance-composition?
Use when deciding between inheritance and composition in object-oriented design. Use when creating class hierarchies or composing objects from smaller components.
Как установить скилл oop-inheritance-composition?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл oop-inheritance-composition запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
frontend-design
Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
от Anthropicwebapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
от Anthropicbrand-guidelines
Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
от Anthropicweb-artifacts-builder
Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…
от Anthropic