Klasser och properties

“The Force is strong in this one… and so are the object-oriented programming principles!”

Welcome back, ung Padawan! Du har lärt dig om The Force of Data (variabler) och The Jedi Arts (metoder). Nu är det dags för det stora steget: att bygga din egen Rebel Alliance med klasser. En klass är som blueprints för att bygga hela rymdskepp, planeter, eller till och med hela galaktiska organisationer!

Vad är en klass? (Think Death Star Construction Plans… but for good)

En klass är som en detaljerad ritning eller mall för att skapa objekt. Precis som Imperial Engineers hade blueprints för Death Star (which worked… twice, unfortunately för dem), har du klasser som blueprints för att skapa olika “things” i din kod.

Tänk på det såhär:

  • Klass = Death Star blueprints (men för good guys)
  • Objekt = Den faktiska Death Star som byggs (multiple ones if needed)
  • Properties = Specifications (diameter, weapon power, vulnerability to small exhaust ports…)
  • Methods = What it can do (destroy planets, get destroyed by farm boys…)

En klass är som att designa en ny typ av Rebel starfighter. Once du har designen klar kan du bygga så många som du vill, varje med sina egna specifika detaljer.

Enkel klass (Your First Rebel Fighter Design)


public class RebelPilot
{
    // Properties - vad varje pilot har (som personal datapads)
    public string Name;
    public int Age;
    public string Homeworld;
    public string Squadron;
    public bool HasForceAbilities;

    // Method - vad piloten kan göra
    public void ReportForDuty()
    {
        Console.WriteLine("Pilot " + Name + " reporting for duty!");
        if (HasForceAbilities)
        {
            Console.WriteLine("May the Force be with me!");
        }
    }
}

This är your blueprint för rebel pilots. Den säger: “Every rebel pilot will have dessa properties och can perform dessa actions.”

Använda en klass (Building Your Fleet)


// Skapa din första pilot från blueprinten
RebelPilot pilot1 = new RebelPilot();

// Ge piloten specific information (customize your fighter)
pilot1.Name = "Luke Skywalker";
pilot1.Age = 19;
pilot1.Homeworld = "Tatooine";
pilot1.Squadron = "Red Squadron";
pilot1.HasForceAbilities = true;

// Låt piloten rapportera för duty
pilot1.ReportForDuty();
// Output: Pilot Luke Skywalker reporting for duty!
//         May the Force be with me!

Flera objekt från samma klass (Building Your Entire Squadron)


// Bygg hela Red Squadron från samma blueprint!
RebelPilot redLeader = new RebelPilot();
redLeader.Name = "Garven Dreis";
redLeader.Age = 32;
redLeader.Homeworld = "Virujansi";
redLeader.Squadron = "Red Squadron";
redLeader.HasForceAbilities = false;

RebelPilot redTwo = new RebelPilot();
redTwo.Name = "Wedge Antilles";
redTwo.Age = 22;
redTwo.Homeworld = "Corellia";
redTwo.Squadron = "Red Squadron";
redTwo.HasForceAbilities = false;

RebelPilot redFive = new RebelPilot();
redFive.Name = "Luke Skywalker";
redFive.Age = 19;
redFive.Homeworld = "Tatooine";
redFive.Squadron = "Red Squadron";
redFive.HasForceAbilities = true;

// All pilots can perform samma actions men med their own personality
redLeader.ReportForDuty();  // Pilot Garven Dreis reporting for duty!
redTwo.ReportForDuty();     // Pilot Wedge Antilles reporting for duty!
redFive.ReportForDuty();    // Pilot Luke Skywalker reporting for duty! May the Force be with me!

Properties - The Modern Jedi Way (Cleaner än Imperial bureaucracy)

Properties är ett modernare och säkrare sätt att handle data i dina klasser. Think of them as secure communication channels instead of open Imperial broadcasts:


public class Starfighter
{
    // Modern properties med { get; set; } - like encrypted communication
    public string Model { get; set; }
    public string Pilot { get; set; }
    public int ShieldStrength { get; set; }
    public double Speed { get; set; }
    public bool HasHyperdrive { get; set; }

    public void LaunchFighter()
    {
        Console.WriteLine(Model + " piloted by " + Pilot + " launching!");
        Console.WriteLine("Shield strength: " + ShieldStrength + "%");

        if (HasHyperdrive)
        {
            Console.WriteLine("Hyperdrive ready för lightspeed!");
        }
    }

    public void DisplaySpecs()
    {
        Console.WriteLine("=== STARFIGHTER SPECS ===");
        Console.WriteLine("Model: " + Model);
        Console.WriteLine("Pilot: " + Pilot);
        Console.WriteLine("Max Speed: " + Speed + " MGLT");
        Console.WriteLine("Shield: " + ShieldStrength + "%");
        Console.WriteLine("Hyperdrive: " + (HasHyperdrive ? "Yes" : "No"));
    }
}

// Användning (Building your custom X-wing):
Starfighter lukesFighter = new Starfighter();
lukesFighter.Model = "T-65 X-wing";
lukesFighter.Pilot = "Luke Skywalker";
lukesFighter.ShieldStrength = 95;
lukesFighter.Speed = 100.0;
lukesFighter.HasHyperdrive = true;

lukesFighter.LaunchFighter();
lukesFighter.DisplaySpecs();

Konstruktorer - Factory Setup (Like Droid Manufacturing on Kamino)

En konstruktor är en special method som runs automatically när du skapar ett nytt objekt. Think of it as the initial programming that every new droid gets:


public class BattleDroid
{
    public string Model { get; set; }
    public string Faction { get; set; }
    public int BattleRating { get; set; }
    public bool IsOperational { get; set; }

    // Konstruktor - runs when each droid is "manufactured"
    public BattleDroid(string droidModel, string allegiance, int combat)
    {
        Model = droidModel;
        Faction = allegiance;
        BattleRating = combat;
        IsOperational = true;  // All droids start operational

        Console.WriteLine("New " + Model + " droid manufactured for " + Faction);
    }

    public void ExecuteOrder()
    {
        if (IsOperational)
        {
            Console.WriteLine(Model + " droid ready för combat! Battle rating: " + BattleRating);
        }
        else
        {
            Console.WriteLine(Model + " droid is offline...");
        }
    }
}

// Nu kan du create droids direkt med their specifications:
BattleDroid rebelDroid = new BattleDroid("R2-D2", "Rebel Alliance", 3);
BattleDroid imperialDroid = new BattleDroid("Imperial Probe Droid", "Galactic Empire", 7);

rebelDroid.ExecuteOrder();   // R2-D2 droid ready för combat! Battle rating: 3
imperialDroid.ExecuteOrder(); // Imperial Probe Droid droid ready för combat! Battle rating: 7

Praktiskt exempel - Galactic Banking System


public class GalacticBankAccount
{
    public string AccountOwner { get; set; }
    public double Credits { get; set; }
    public string AccountNumber { get; set; }
    public string HomePlanet { get; set; }
    public bool IsFrozenByEmpire { get; set; }

    // Konstruktor för new accounts
    public GalacticBankAccount(string owner, string homeworld, string accountNum)
    {
        AccountOwner = owner;
        HomePlanet = homeworld;
        AccountNumber = accountNum;
        Credits = 1000.0;  // Starting bonus (Rebellion recruitment incentive)
        IsFrozenByEmpire = false;

        Console.WriteLine("New galactic account opened för " + owner + " från " + homeworld);
    }

    // Deposit credits (smuggling profits, reward money, etc.)
    public void DepositCredits(double amount)
    {
        if (IsFrozenByEmpire)
        {
            Console.WriteLine("Account frozen by Imperial decree! No transactions allowed!");
            return;
        }

        if (amount > 0)
        {
            Credits += amount;
            Console.WriteLine("Deposited " + amount + " credits. New balance: " + Credits + " credits");

            if (amount > 100000)
            {
                Console.WriteLine("Large deposit detected! Empire may be watching...");
            }
        }
        else
        {
            Console.WriteLine("Invalid deposit amount. Are you trying to pull a Lando?");
        }
    }

    // Withdraw credits (equipment, bribery, cantina tabs...)
    public bool WithdrawCredits(double amount)
    {
        if (IsFrozenByEmpire)
        {
            Console.WriteLine("Account frozen! The Empire has blocked all transactions!");
            return false;
        }

        if (amount > 0 && amount <= Credits)
        {
            Credits -= amount;
            Console.WriteLine("Withdrew " + amount + " credits. Remaining balance: " + Credits + " credits");

            if (Credits < 100)
            {
                Console.WriteLine("Warning: Low balance! Time för another smuggling run?");
            }
            return true;
        }
        else if (amount > Credits)
        {
            Console.WriteLine("Insufficient credits! You need " + (amount - Credits) + " more credits.");
            Console.WriteLine("Maybe ask Lando för a loan? (Good luck with that...)");
            return false;
        }
        else
        {
            Console.WriteLine("Invalid withdrawal amount. What are you, a malfunctioning droid?");
            return false;
        }
    }

    public void FreezeByEmpire()
    {
        IsFrozenByEmpire = true;
        Console.WriteLine("ACCOUNT FROZEN by Imperial Security Bureau!");
        Console.WriteLine("Reason: Suspected Rebel sympathizer");
    }

    public void ShowAccountStatus()
    {
        Console.WriteLine("\n=== GALACTIC BANK ACCOUNT ===");
        Console.WriteLine("Owner: " + AccountOwner);
        Console.WriteLine("Home Planet: " + HomePlanet);
        Console.WriteLine("Account: " + AccountNumber);
        Console.WriteLine("Balance: " + Credits + " Galactic Standard Credits");
        Console.WriteLine("Status: " + (IsFrozenByEmpire ? "FROZEN BY EMPIRE" : "Active"));

        if (Credits > 500000)
        {
            Console.WriteLine("Wealth Level: Rich som Jabba the Hutt");
        }
        else if (Credits > 50000)
        {
            Console.WriteLine("Wealth Level: Comfortable smuggler");
        }
        else if (Credits > 5000)
        {
            Console.WriteLine("Wealth Level: Average spacer");
        }
        else
        {
            Console.WriteLine("Wealth Level: Poor som moisture farmer");
        }
    }
}

// Användning (Setting up accounts för the crew):
GalacticBankAccount hanAccount = new GalacticBankAccount("Han Solo", "Corellia", "CORR-2187");
GalacticBankAccount lukeAccount = new GalacticBankAccount("Luke Skywalker", "Tatooine", "TAT-1138");

// Some typical galactic transactions
hanAccount.DepositCredits(75000);    // Successful smuggling run
hanAccount.WithdrawCredits(15000);   // Millennium Falcon repairs (again...)

lukeAccount.DepositCredits(200000);  // Reward för destroying Death Star
lukeAccount.WithdrawCredits(50000);  // New lightsaber materials

// Empire strikes back...
hanAccount.FreezeByEmpire();         // Han gets in trouble (as usual)
hanAccount.WithdrawCredits(1000);    // This won't work now

// Check everyone's status
hanAccount.ShowAccountStatus();
lukeAccount.ShowAccountStatus();

Object Initializers - The Quick Setup (Like R2-D2’s rapid programming)


// Instead of setting properties one by one...
RebelPilot pilot = new RebelPilot();
pilot.Name = "Wedge Antilles";
pilot.Age = 22;
pilot.Homeworld = "Corellia";

// You can set everything at once (faster än lightspeed):
RebelPilot wedge = new RebelPilot
{
    Name = "Wedge Antilles",
    Age = 22,
    Homeworld = "Corellia",
    Squadron = "Red Squadron",
    HasForceAbilities = false
};

// Perfect för creating multiple objects quickly
RebelPilot biggs = new RebelPilot
{
    Name = "Biggs Darklighter",
    Age = 18,
    Homeworld = "Tatooine",
    Squadron = "Red Squadron",
    HasForceAbilities = false
};

Varför använda klasser? (The Rebel Alliance Philosophy)

1. Organisation (Better än Imperial bureaucracy)

Without classes (The Imperial way - chaotic och inefficient):


// Separata variables för every pilot - nightmare att manage!
string pilot1Name = "Luke";
int pilot1Age = 19;
string pilot1Homeworld = "Tatooine";
bool pilot1ForceAbilities = true;

string pilot2Name = "Wedge";
int pilot2Age = 22;
string pilot2Homeworld = "Corellia";
bool pilot2ForceAbilities = false;

// Detta blir quickly unmanageable... som Imperial Death Star management

Med classes (The Rebel way - organized och scalable):


public class Squadron
{
    public string Name { get; set; }
    public List<RebelPilot> Pilots { get; set; }
    public int MissionSuccessRate { get; set; }

    public Squadron(string squadronName)
    {
        Name = squadronName;
        Pilots = new List<RebelPilot>();
        MissionSuccessRate = 0;
    }

    public void AddPilot(RebelPilot pilot)
    {
        Pilots.Add(pilot);
        pilot.Squadron = Name;
        Console.WriteLine(pilot.Name + " assigned to " + Name);
    }

    public void LaunchMission(string missionName)
    {
        Console.WriteLine("\n=== " + Name.ToUpper() + " MISSION LAUNCH ===");
        Console.WriteLine("Mission: " + missionName);
        Console.WriteLine("Squadron Status:");

        foreach (RebelPilot pilot in Pilots)
        {
            pilot.ReportForDuty();
        }

        Console.WriteLine("All pilots ready! May the Force be with us!");
    }
}

// Now you can manage entire squadrons easily:
Squadron redSquadron = new Squadron("Red Squadron");
redSquadron.AddPilot(new RebelPilot { Name = "Luke Skywalker", HasForceAbilities = true });
redSquadron.AddPilot(new RebelPilot { Name = "Wedge Antilles", HasForceAbilities = false });
redSquadron.LaunchMission("Death Star Attack");

2. Reusability (Build once, use många times)


// Create different types of starfighters från samma basic structure
Starfighter xwing1 = new Starfighter { Model = "X-wing", Pilot = "Luke" };
Starfighter xwing2 = new Starfighter { Model = "X-wing", Pilot = "Wedge" };
Starfighter ywing1 = new Starfighter { Model = "Y-wing", Pilot = "Gold Leader" };

// All use samma methods men med different data
xwing1.LaunchFighter();
xwing2.LaunchFighter();
ywing1.LaunchFighter();

Vanliga misstag att undvika (Don’t make Jar Jar-level mistakes)

Misstag 1: Glömma ‘new’ keyword (Like forgetting to fuel your starfighter)


// FEL - declaring utan creating (starfighter exists only in blueprints)
RebelPilot pilot;
pilot.Name = "Luke";  // CRASH! No actual pilot object exists yet

// RÄTT - actually build the starfighter first
RebelPilot pilot = new RebelPilot();
pilot.Name = "Luke";  // Now we have an actual pilot!

Misstag 2: Trying to use Class directly instead of Object (Like giving orders to Death Star blueprints instead of actual Death Star)


// FEL - trying to use the class itself
RebelPilot.Name = "Luke";  // FEL! RebelPilot är blueprint, inte actual pilot

// RÄTT - create specific pilot object first
RebelPilot actualPilot = new RebelPilot();
actualPilot.Name = "Luke";  // Perfect! Now Luke exists as actual pilot

Misstag 3: Null Reference Exceptions (Like sending pilots on missions utan starfighters)


// FEL - creating reference but not object
RebelPilot pilot = null;  // Just a empty hangar
pilot.Name = "Luke";      // CRASH! No pilot exists to name

// RÄTT - actually create the pilot
RebelPilot pilot = new RebelPilot();  // Pilot manufactured and ready
pilot.Name = "Luke";                  // Now he can have a name

Advanced Class Features (For Future Jedi Masters)

ToString Override (Custom identification like pilot call signs)


public class RebelPilot
{
    public string Name { get; set; }
    public string Callsign { get; set; }
    public string Squadron { get; set; }

    // Custom ToString för better identification
    public override string ToString()
    {
        return $"{Callsign} ({Name}) - {Squadron}";
    }
}

// Usage:
RebelPilot luke = new RebelPilot
{
    Name = "Luke Skywalker",
    Callsign = "Red Five",
    Squadron = "Red Squadron"
};

Console.WriteLine(luke);  // Output: Red Five (Luke Skywalker) - Red Squadron

Sammanfattning (What you learned about building your Rebel Alliance)

  • Klasser är blueprints för creating objects (som Death Star plans, men för good)
  • Objects är actual instances built från class blueprints (faktiska starfighters)
  • Properties ({ get; set; }) är modern way to store och access data (secure comm channels)
  • Konstruktors automatically initialize new objects (droid manufacturing process)
  • Object Initializers let you set multiple properties quickly (rapid deployment)
  • Classes organize related data och functionality (like organizing Rebel Alliance structure)
  • Always använd ‘new’ to create objects (build actual starfighters, inte just blueprints)

Remember: “In my experience, there’s no such thing as luck” - Obi-Wan Kenobi. Good class design isn’t luck - it’s careful planning och organization, som building successful Rebel Alliance!

Classes are the foundation för building complex applications. Master them, och you’ll be ready för större battles ahead!

May the Classes be with you!

Föregående: Kapitel 2 - Metoder: The Jedi Arts Nästa: Kapitel 4 - If-satser och loopar: The Tactical Decisions

[{"content": "Merge and rewrite Chapter 1 with Star Wars theme and chill humor", "status": "completed", "activeForm": "Creating Star Wars themed Chapter 1"}, {"content": "Merge and rewrite Chapter 2 with Star Wars theme", "status": "completed", "activeForm": "Creating Star Wars themed Chapter 2"}, {"content": "Merge and rewrite Chapter 3 with Star Wars theme", "status": "completed", "activeForm": "Creating Star Wars themed Chapter 3"}, {"content": "Merge and rewrite Chapter 4 with Star Wars theme", "status": "in_progress", "activeForm": "Creating Star Wars themed Chapter 4"}, {"content": "Merge and rewrite Chapter 5 with Star Wars theme", "status": "pending", "activeForm": "Creating Star Wars themed Chapter 5"}, {"content": "Delete the original grammar articles after completion", "status": "pending", "activeForm": "Cleaning up original files"}]

Upp

Upp


Licens: Apache 2.0 | © 2023 Marcus Medina, Campus Mölndal. Alla rättigheter förbehållna.
Du får använda och modifiera detta verk enligt villkoren i Apache License, Version 2.0. Du får inte använda detta verk för kommersiella ändamål utan tillstånd från upphovsmannen.