Classes and Inheritance

Learn about classes and inheritance in C#. Understand how to create classes and use inheritance to reuse code efficiently.

What is a Class?

A class is a blueprint that groups variables and functions together to create an object. Used when creating players, enemies, items, etc. in games.

public class Human : MonoBehaviour
{
    public string myName;
    public bool isSolo;
    
    public void Eat() {
        Debug.Log("Eating");
    }
    
    private void Sleep() {
        Debug.Log("Sleeping");
    }
}

What is Inheritance?

Inheritance is a way to create a new class by taking all functionality from an existing class. Child classes can use all variables and functions from parent classes.

// Parent class (Human)
public class Human : MonoBehaviour
{
    public string myName;
    public void Eat() {
        Debug.Log("Eating");
    }
}

// Child class (GwangSeub) - inherits from Human
public class GwangSeub : Human
{
    void Start()
    {
        myName = "Ma GwangSeub";  // Can use parent class variable
        Eat();              // Can use parent class function
    }
}

Advantages of Inheritance

  • Code reuse: No need to rewrite parent class code
  • Consistency: Similar objects share the same functionality
  • Maintainability: Modify parent class to apply to all child classes

Practical Example: Car Class

// Parent class: Car
public class Car : MonoBehaviour
{
    public string carColor;
    public int carMaxSpeed;
    
    public void Driving() {
        Debug.Log("Driving");
    }
    
    public void pushBrake() {
        Debug.Log("Brake");
    }
}

// Child class: BMW (inherits from Car)
public class BMW : Car
{
    void Start()
    {
        carColor = "Black";      // Use parent class variable
        carMaxSpeed = 250;        // Use parent class variable
        Driving();                // Use parent class function
    }
}

Inheritance Relationship

  • Parent Class: Class that provides inheritance (Human, Car)
  • Child Class: Class that receives inheritance (GwangSeub, BMW)
  • Inheritance syntax: class ChildClass : ParentClass

← Back to Table of Contents