<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ classes - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ classes - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 15 May 2026 22:30:26 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/classes/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The C# Class Handbook – Types of Classes with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Classes are the fundamental building blocks of object-oriented programming in C#. They allow you to create reusable and modular code by grouping related data and functions. Different types of classes serve various purposes. For instance, organizing y... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/classes-in-c-sharp-handbook-with-examples/</link>
                <guid isPermaLink="false">67659959cfcbe6eba5ecf6dc</guid>
                
                    <category>
                        <![CDATA[ C# ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dotnet ]]>
                    </category>
                
                    <category>
                        <![CDATA[ classes ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Isaiah Clifford Opoku ]]>
                </dc:creator>
                <pubDate>Fri, 20 Dec 2024 16:20:41 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1734711601436/b4de90be-1d93-4d8d-a4ed-ae09b192ef5c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Classes are the fundamental building blocks of object-oriented programming in C#. They allow you to create reusable and modular code by grouping related data and functions.</p>
<p>Different types of classes serve various purposes. For instance, organizing your logic to make your code easier to navigate is helpful when building an application.</p>
<p>You can group or separate your code into classes, and through inheritance, you can utilize different classes as needed. Classes help encapsulate your code, enabling you to reuse your logic in other application parts. Classes have many functionalities, and we will explore some of them in detail.</p>
<p>In this guide, we'll explore various types of classes in C# and how you can use them to create efficient and maintainable code.</p>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>Before we proceed, you should have the following:</p>
<ol>
<li><p><strong>Basic knowledge of C#</strong>: you should understand C# syntax and basic programming constructs like variables, loops, and conditionals.</p>
</li>
<li><p><strong>Familiarity with Object-Oriented Programming (OOP) concepts</strong>: you should know how to work with classes, objects, inheritance, polymorphism, encapsulation, and abstraction.</p>
</li>
<li><p><strong>Familiarity with access modifiers</strong>: you should understand public, private, internal, and protected access modifiers.</p>
</li>
<li><p><strong>Experience with C# IDE/Environment</strong>: you should be able to write and run C# programs using an IDE like Visual Studio.</p>
</li>
</ol>
<p>If you want to learn more about C#, you can check out my YouTube channel: <a target="_blank" href="https://www.youtube.com/@CliffTech">CliffTech</a>.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-static-classes-in-c-sharp">Static Classes in C Sharp</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-sealed-classes-in-c-sharp">Sealed Classes in C Sharp</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-concrete-classes-in-c-sharp">Concrete Classes in C Sharp</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-abstract-classes-in-c-sharp">Abstract Classes in C Sharp</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-singleton-classes-in-c-sharp">Singleton Classes in C Sharp</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-generic-classes-in-c-sharp">Generic Classes in C Sharp</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-internal-classes-in-c-sharp">Internal Classes in C Sharp</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-nested-classes-in-c-sharp">Nested Classes in C Sharp</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-partial-classes-in-c-sharp">Partial Classes in C Sharp</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<p>The first type of class we’ll discuss is the Static Class. Let’s dive in.</p>
<h2 id="heading-static-classes-in-c-sharp">Static Classes in C Sharp</h2>
<p>Static classes are a special type of class in C# designed to provide a collection of related utility methods and properties that do not rely on instance data.</p>
<p>Static classes in C# are a unique type of class designed to house a collection of related utility methods and properties that don't depend on instance data.</p>
<p>Unlike regular classes, static classes cannot be instantiated, and they exclusively contain static members. This characteristic means they cannot be inherited, making them perfect for organizing stateless methods that don't require the features of object-oriented programming.</p>
<p>In essence, when we refer to stateless grouping, it implies that there's no need to create an instance to call a static method – you can simply use the class or method name directly. This approach provides a clear and efficient way to manage utility functions, enhancing code organization and accessibility.</p>
<h3 id="heading-example-of-a-static-class-in-c">Example of a Static Class in C</h3>
<p>Here's an example of a static class in C#:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">StaticClasses</span>
{
<span class="hljs-comment">// Define a static class</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">MathUtils</span>
    {
        <span class="hljs-comment">// Static method to add two numbers</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Add</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b</span>)</span>
        {
            <span class="hljs-keyword">return</span> a + b;
        }

        <span class="hljs-comment">// Static method to subtract two numbers</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Subtract</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b</span>)</span>
        {
            <span class="hljs-keyword">return</span> a - b;
        }

       <span class="hljs-comment">// Static method to multiply two numbers</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">Multiply</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b</span>)</span>
        {
            <span class="hljs-keyword">return</span> a * b;
        }
    }
}
</code></pre>
<p>In this example:</p>
<ul>
<li><p>The <code>MathUtils</code> class is defined as <code>static</code>, meaning it cannot be instantiated.</p>
</li>
<li><p>It contains three static methods: <code>Add</code>, <code>Subtract</code>, and <code>Multiply</code>.</p>
</li>
<li><p>These methods can be called directly on the <code>MathUtils</code> class without creating an instance.</p>
</li>
</ul>
<p>Before you can use this, you need to call it in your <code>Program.cs</code>. When you create any C# application, the entry point is <code>Program.cs</code>. You’ll need to go there and make sure to call these classes so that you can execute them. This is what we will be doing for the rest of the section.</p>
<h3 id="heading-how-to-use-static-methods-in-programcs">How to Use Static Methods in <code>Program.cs</code></h3>
<p>Now you can use the static methods defined in the <code>MathUtils</code> class as follows:</p>
<pre><code class="lang-csharp">
 <span class="hljs-comment">// program.cs</span>
<span class="hljs-keyword">namespace</span> <span class="hljs-title">StaticClasses</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
             <span class="hljs-comment">// Call static methods from the MathUtils class</span>
            <span class="hljs-keyword">int</span> sum = MathUtils.Add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>);
            <span class="hljs-comment">// Call the static method Subtract from the MathUtils class</span>
            <span class="hljs-keyword">int</span> difference = MathUtils.Subtract(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>);

            <span class="hljs-comment">// Call the static method Multiply from the MathUtils class</span>
            <span class="hljs-keyword">int</span> product = MathUtils.Multiply(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>);

            <span class="hljs-comment">// Display the results of the sum method</span>
            Console.WriteLine(<span class="hljs-string">$"Sum: <span class="hljs-subst">{sum}</span>"</span>); <span class="hljs-comment">// Output: 8</span>
            <span class="hljs-comment">// Display the results of the difference method</span>
            Console.WriteLine(<span class="hljs-string">$"Difference: <span class="hljs-subst">{difference}</span>"</span>); <span class="hljs-comment">// Output: 2</span>
            <span class="hljs-comment">// Display the results of the product method</span>
            Console.WriteLine(<span class="hljs-string">$"Product: <span class="hljs-subst">{product}</span>"</span>);  <span class="hljs-comment">// Output: 15</span>
        }
    }
}
</code></pre>
<h3 id="heading-when-to-use-statice-classes-vs-methods">When to Use Statice Classes vs Methods</h3>
<p>To decide when to use static classes or methods in C#, consider the following guidelines:</p>
<ol>
<li><p><strong>Use Static Classes when:</strong></p>
<ul>
<li><p>You need a collection of utility or helper methods that do not require any instance data.</p>
</li>
<li><p>The methods and properties are stateless and can be accessed globally without creating an object.</p>
</li>
<li><p>You want to group related functions that are not tied to a specific object state.</p>
</li>
<li><p>You need to ensure that the class cannot be instantiated or inherited.</p>
</li>
</ul>
</li>
<li><p><strong>Use Static Methods when:</strong></p>
<ul>
<li><p>You have a class that is mostly instance-based, but you need a few methods that do not depend on instance data.</p>
</li>
<li><p>The method performs a task that is independent of any object state and can be executed without an instance.</p>
</li>
<li><p>You want to provide a utility function within a class that can be accessed without creating an object of that class.</p>
</li>
</ul>
</li>
</ol>
<p>By using static classes and methods appropriately, you can enhance code organization, improve performance by avoiding unnecessary object creation, and ensure that certain functionalities are easily accessible throughout your application.</p>
<h3 id="heading-key-points-to-remember-about-static-classes-in-c">Key Points to Remember About Static Classes in C</h3>
<ul>
<li><p><strong>Cannot be Instantiated</strong>: You cannot create objects from a static class.</p>
</li>
<li><p><strong>Only static members</strong>: Static classes can only have static members. They do not support instance methods or fields.</p>
</li>
<li><p><strong>Sealed by default</strong>: Static classes are automatically sealed, so they cannot be inherited.</p>
</li>
<li><p><strong>Utility and helper methods</strong>: Static classes are usually used to group related utility or helper methods that don't need an object state.</p>
</li>
</ul>
<p>Static classes help organize and access utility methods and properties clearly and simply, making them important for creating efficient and maintainable code.</p>
<h2 id="heading-sealed-classes-in-c-sharp">Sealed Classes in C Sharp</h2>
<p>Sealed classes are a special type of class in C# that cannot be inherited. You can use them to prevent other classes from deriving from them, which can be useful for creating immutable types or ensuring that a class's behavior remains unchanged.</p>
<p>By sealing a class, you ensure that it cannot be modified or extended, making it useful for scenarios where you want to provide a specific implementation without allowing further alterations.</p>
<h3 id="heading-example-of-a-sealed-class-in-c">Example of a Sealed Class in C</h3>
<p>Here's an example of a sealed class in C#:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">SealedClasses</span>
{

    <span class="hljs-comment">// Define an abstract class</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span>
    {
        <span class="hljs-comment">// Abstract method to calculate the area</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">double</span> <span class="hljs-title">CalculateArea</span>(<span class="hljs-params"></span>)</span>;
    }

     <span class="hljs-comment">// Define a sealed class</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">sealed</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Rectangle</span> : <span class="hljs-title">Shape</span>
    {

        <span class="hljs-comment">//  Properties</span>
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> Width { <span class="hljs-keyword">get</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> Height { <span class="hljs-keyword">get</span>; }

        <span class="hljs-comment">// Constructor</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Rectangle</span>(<span class="hljs-params"><span class="hljs-keyword">double</span> width, <span class="hljs-keyword">double</span> height</span>)</span>
        {
            Width = width;
            Height = height;
        }

       <span class="hljs-comment">// Implement the CalculateArea method</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">double</span> <span class="hljs-title">CalculateArea</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">return</span> Width * Height;
        }
    }
}
</code></pre>
<p>In this example:</p>
<ul>
<li><p>The <code>Shape</code> class is an abstract base class with an abstract method <code>CalculateArea()</code>.</p>
</li>
<li><p>The <code>Rectangle</code> class inherits from <code>Shape</code> and provides an implementation for <code>CalculateArea()</code>.</p>
</li>
<li><p>The <code>Rectangle</code> class is sealed, which means it cannot be inherited from. This ensures that the class's implementation cannot be modified or extended.</p>
</li>
</ul>
<h3 id="heading-how-to-use-the-sealed-rectangle-class-in-the-programcs">How to Use the Sealed Rectangle Class in the Program.cs</h3>
<p>Here's how you can use the <code>Rectangle</code> class in a <code>Program.cs</code> file:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">SealedClasses</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            Rectangle rectangle = <span class="hljs-keyword">new</span> Rectangle(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>);
            <span class="hljs-keyword">double</span> area = rectangle.CalculateArea();

            Console.WriteLine(<span class="hljs-string">$"Area of the rectangle: <span class="hljs-subst">{area}</span>"</span>); <span class="hljs-comment">// Output: Area of the rectangle: 15</span>
        }
    }
}
</code></pre>
<p>In this example, the <code>Rectangle</code> class is sealed to ensure that its behavior cannot be changed through inheritance. This guarantees that the <code>Rectangle</code> class's implementation of <code>CalculateArea()</code> stays the same, which helps maintain consistent behavior.</p>
<h3 id="heading-when-to-use-sealed-classes">When to Use Sealed Classes</h3>
<p>Sealed classes are particularly useful in the following contexts:</p>
<ol>
<li><p><strong>Framework development</strong>: When developing frameworks or libraries, you might use sealed classes to lock down certain classes that are not intended to be extended by users. This helps maintain control over the framework's behavior and ensures that users cannot introduce bugs or inconsistencies by extending these classes.</p>
</li>
<li><p><strong>Preventing inheritance</strong>: If a class is designed to be a specific implementation with no need for further customization or extension, sealing it prevents other developers from creating subclasses that might alter its intended functionality.</p>
</li>
<li><p><strong>Finalizing class design</strong>: When a class has reached a point where its design is considered complete and no further changes or extensions are anticipated, sealing it can signal to other developers that the class should be used as-is.</p>
</li>
<li><p><strong>Avoiding overriding</strong>: In scenarios where overriding methods could lead to incorrect behavior or security issues, sealing the class ensures that its methods cannot be overridden, preserving the original logic and functionality.</p>
</li>
</ol>
<h3 id="heading-key-points-to-remember-about-sealed-classes">Key Points to Remember About Sealed Classes</h3>
<ul>
<li><p><strong>No inheritance</strong>: Sealed classes cannot be inherited, ensuring their behavior stays the same.</p>
</li>
<li><p><strong>Prevent modification</strong>: They prevent further inheritance, avoiding accidental changes or extensions.</p>
</li>
<li><p><strong>Immutable and specific</strong>: Sealed classes are useful for creating immutable classes or when you need a specific, unchangeable implementation.</p>
</li>
</ul>
<h3 id="heading-sealed-classes-vs-static-classes">Sealed Classes vs. Static Classes</h3>
<p>You might wonder why we need sealed classes if static classes are already sealed. The key differences are:</p>
<ul>
<li><p><strong>Static Classes</strong> are sealed and cannot be instantiated. They are used for grouping static methods and properties.</p>
</li>
<li><p><strong>Sealed Classes</strong> can be instantiated but cannot be inherited. This allows for creating objects that are protected from further subclassing.</p>
</li>
</ul>
<p>Sealed classes offer flexibility in creating classes that can be used directly without the risk of modification through inheritance.</p>
<h2 id="heading-concrete-classes-in-c-sharp">Concrete Classes in C Sharp</h2>
<p>Concrete classes are essential in <code>object-oriented programming</code> in C#. They are fully implemented classes that you can use to create objects directly.</p>
<p>Unlike <code>abstract classes</code> or <code>interfaces</code>, concrete classes have complete implementations of all their methods and properties, making them versatile and fundamental to most C# applications.</p>
<p>A concrete class is not abstract. It includes full implementations of all its members—methods, properties, fields, and so on—and can be used to create objects. These classes represent real-world entities or concepts in your application, encapsulating both data (stored in fields or properties) and behavior (defined by methods).</p>
<h3 id="heading-example-defining-a-concrete-class-in-c">Example: Defining a Concrete Class in C</h3>
<p>Here's a simple example of a concrete class in C#:</p>
<pre><code class="lang-csharp">

<span class="hljs-comment">// Define a concrete class</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Speak</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"The animal makes a sound."</span>);
    }
}

<span class="hljs-comment">// Define a derived class that inherits from the Animal class</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> : <span class="hljs-title">Animal</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Bark</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"The dog barks."</span>);
    }
}
</code></pre>
<p>In this example, the <code>Animal</code> class is a concrete class with a method <code>Speak</code> that represents a generic sound made by any animal. The <code>Dog</code> class inherits from <code>Animal</code> and adds a <code>Bark</code> method to represent a sound specific to dogs. Both <code>Animal</code> and <code>Dog</code> are concrete classes because they can be instantiated and used to create objects.</p>
<h3 id="heading-how-to-instantiate-and-use-concrete-classes">How to Instantiate and Use Concrete Classes</h3>
<p>Here's how you can use the <code>Dog</code> class in a <code>Program.cs</code> file:</p>
<pre><code class="lang-csharp">
<span class="hljs-comment">// program.cs</span>
<span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
    {
        <span class="hljs-comment">// Create an instance of the Dog class</span>
        Dog myDog = <span class="hljs-keyword">new</span> Dog();

        <span class="hljs-comment">// Call the inherited method</span>
        myDog.Speak(); <span class="hljs-comment">// Output: The animal makes a sound.</span>

        <span class="hljs-comment">// Call the method defined in the Dog class</span>
        myDog.Bark();  <span class="hljs-comment">// Output: The dog barks.</span>
    }
}
</code></pre>
<p>In this example, we create an instance of the <code>Dog</code> class called <code>myDog</code>. We first call the <code>Speak</code> method, which is inherited from the <code>Animal</code> class, and then the <code>Bark</code> method from the <code>Dog</code> class. This shows how concrete classes can include both inherited and unique behaviors.</p>
<h3 id="heading-real-world-example-concrete-class-for-a-product">Real-World Example: Concrete Class for a Product</h3>
<p>To illustrate the practical application of concrete classes, consider the following example of a <code>Product</code> class:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Define a concrete class for a product</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Product</span>
{
    <span class="hljs-comment">// Data properties</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Price { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-comment">// Method to display product information</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayInfo</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Product: <span class="hljs-subst">{Name}</span>, Price: <span class="hljs-subst">{Price:C}</span>"</span>);
    }
}
</code></pre>
<p>This <code>Product</code> class is a concrete class with properties <code>Name</code> and <code>Price</code> to store information about a product. The <code>DisplayInfo</code> method provides a way to display the product’s details.</p>
<h4 id="heading-how-to-use-the-product-class">How to Use the <code>Product</code> Class</h4>
<p>Here's how you can use the <code>Product</code> class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
    {
        <span class="hljs-comment">// Create an instance of the Product class</span>
        Product product = <span class="hljs-keyword">new</span> Product
        {
            Name = <span class="hljs-string">"Laptop"</span>,
            Price = <span class="hljs-number">1299.99</span>m
        };

        <span class="hljs-comment">// Display product information</span>
        product.DisplayInfo(); <span class="hljs-comment">// Output: Product: Laptop, Price: $1,299.99</span>
    }
}
</code></pre>
<p>In this scenario, the <code>Product</code> class is used to create a <code>product</code> object. The <code>DisplayInfo</code> method is called to show the product's name and price. This demonstrates how concrete classes are used to model and work with real-world data.</p>
<h3 id="heading-key-points-to-remember-about-concrete-classes">Key Points to Remember About Concrete Classes</h3>
<ul>
<li><p><strong>Instantiable</strong>: Concrete classes can be instantiated, allowing you to create objects that represent specific entities or concepts in your application.</p>
</li>
<li><p><strong>Complete implementation</strong>: Concrete classes provide full implementations of all methods and properties, unlike abstract classes or interfaces.</p>
</li>
<li><p><strong>Common use</strong>: They are the most common type of class in C#, used to define objects with specific behavior and data.</p>
</li>
</ul>
<p>Concrete classes are essential for C# development, enabling you to define and work with objects that model real-world entities within your applications. Understanding how to effectively use concrete classes is crucial for building robust, object-oriented software.</p>
<h2 id="heading-abstract-classes-in-c-sharp">Abstract Classes in C Sharp</h2>
<p>In C#, abstract classes are a powerful feature that allow you to define a blueprint for other classes without providing complete implementations. They serve as base classes that cannot be instantiated directly but can be inherited by other classes that will provide specific implementations for the abstract methods defined within them. This design helps enforce consistency across related classes while allowing flexibility in how certain behaviors are implemented.</p>
<h3 id="heading-what-does-instantiated-mean">What Does "Instantiated" Mean?</h3>
<p>Before exploring abstract classes, let's clarify what it means to instantiate a class. Instantiation is the process of creating an object from a class. When you use the <code>new</code> keyword in C#, you are creating an instance (or object) of that class.</p>
<p>But abstract classes cannot be instantiated directly. They must be inherited by a non-abstract (concrete) class that provides implementations for the abstract methods.</p>
<h3 id="heading-understanding-abstract-classes-and-abstract-methods">Understanding Abstract Classes and Abstract Methods</h3>
<p><strong>Abstract classes</strong> are classes you can't create objects from directly. They act as templates for other classes. They can have both complete methods and methods without a body (abstract methods). Abstract classes help set up a common interface and shared behavior for related classes.</p>
<p><strong>Abstract methods</strong>, on the other hand, are methods in an abstract class that don't have a body. Any non-abstract class that inherits from the abstract class must provide a body for these methods. This ensures all subclasses have a consistent interface.</p>
<h3 id="heading-real-world-example-bank-account-management">Real-World Example: Bank Account Management</h3>
<p>Let's explore a real-world example to illustrate the concept of abstract classes and abstract methods in C#.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> System;

<span class="hljs-comment">// define an abstract class</span>
<span class="hljs-keyword">namespace</span> <span class="hljs-title">AbstractClasses</span>
{
    <span class="hljs-comment">// Abstract class</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BankAccount</span>
    {
        <span class="hljs-comment">// Properties</span>
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> AccountNumber { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Balance { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">protected</span> <span class="hljs-keyword">set</span>; }

        <span class="hljs-comment">// Constructor</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">BankAccount</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> accountNumber, <span class="hljs-keyword">decimal</span> initialBalance</span>)</span>
        {
            AccountNumber = accountNumber;
            Balance = initialBalance;
        }

        <span class="hljs-comment">// Abstract methods</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Deposit</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> amount</span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Withdraw</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> amount</span>)</span>;
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayAccountInfo</span>(<span class="hljs-params"></span>)</span>;
    }

    <span class="hljs-comment">// Derived class: SavingsAccount</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SavingsAccount</span> : <span class="hljs-title">BankAccount</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">decimal</span> interestRate;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SavingsAccount</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> accountNumber, <span class="hljs-keyword">decimal</span> initialBalance, <span class="hljs-keyword">decimal</span> interestRate</span>)
            : <span class="hljs-title">base</span>(<span class="hljs-params">accountNumber, initialBalance</span>)</span>
        {
            <span class="hljs-keyword">this</span>.interestRate = interestRate;
        }

        <span class="hljs-comment">// Implementing abstract methods</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Deposit</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> amount</span>)</span>
        {
            Balance += amount;
            Console.WriteLine(<span class="hljs-string">$"Deposited <span class="hljs-subst">{amount}</span> to Savings Account <span class="hljs-subst">{AccountNumber}</span>. New Balance: <span class="hljs-subst">{Balance}</span>"</span>);
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Withdraw</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> amount</span>)</span>
        {
            <span class="hljs-keyword">if</span> (amount &gt; Balance)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException(<span class="hljs-string">"Insufficient funds."</span>);
            }
            Balance -= amount;
            Console.WriteLine(<span class="hljs-string">$"Withdrew <span class="hljs-subst">{amount}</span> from Savings Account <span class="hljs-subst">{AccountNumber}</span>. New Balance: <span class="hljs-subst">{Balance}</span>"</span>);
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayAccountInfo</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"Savings Account <span class="hljs-subst">{AccountNumber}</span> - Balance: <span class="hljs-subst">{Balance}</span>, Interest Rate: <span class="hljs-subst">{interestRate}</span>%"</span>);
        }
    }

    <span class="hljs-comment">// Derived class: CheckingAccount</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CheckingAccount</span> : <span class="hljs-title">BankAccount</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">decimal</span> overdraftLimit;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CheckingAccount</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> accountNumber, <span class="hljs-keyword">decimal</span> initialBalance, <span class="hljs-keyword">decimal</span> overdraftLimit</span>)
            : <span class="hljs-title">base</span>(<span class="hljs-params">accountNumber, initialBalance</span>)</span>
        {
            <span class="hljs-keyword">this</span>.overdraftLimit = overdraftLimit;
        }

        <span class="hljs-comment">// Implementing abstract methods</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Deposit</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> amount</span>)</span>
        {
            Balance += amount;
            Console.WriteLine(<span class="hljs-string">$"Deposited <span class="hljs-subst">{amount}</span> to Checking Account <span class="hljs-subst">{AccountNumber}</span>. New Balance: <span class="hljs-subst">{Balance}</span>"</span>);
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Withdraw</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> amount</span>)</span>
        {
            <span class="hljs-keyword">if</span> (amount &gt; Balance + overdraftLimit)
            {
                <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException(<span class="hljs-string">"Overdraft limit exceeded."</span>);
            }
            Balance -= amount;
            Console.WriteLine(<span class="hljs-string">$"Withdrew <span class="hljs-subst">{amount}</span> from Checking Account <span class="hljs-subst">{AccountNumber}</span>. New Balance: <span class="hljs-subst">{Balance}</span>"</span>);
        }

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DisplayAccountInfo</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"Checking Account <span class="hljs-subst">{AccountNumber}</span> - Balance: <span class="hljs-subst">{Balance}</span>, Overdraft Limit: <span class="hljs-subst">{overdraftLimit}</span>"</span>);
        }
    }
}
</code></pre>
<p>In this example, the <code>BankAccount</code> class is an abstract class that defines a common interface for different types of bank accounts. It includes abstract methods like <code>Deposit</code>, <code>Withdraw</code>, and <code>DisplayAccountInfo</code>, which must be implemented by any class that inherits from <code>BankAccount</code>.</p>
<p>The <code>SavingsAccount</code> and <code>CheckingAccount</code> classes inherit from <code>BankAccount</code> and provide specific implementations for these abstract methods. This design enforces that every type of bank account must implement deposit, withdrawal, and display functions, while still allowing each account type to implement these functions in a way that makes sense for that specific type.</p>
<h3 id="heading-how-to-use-abstract-classes-in-a-program">How to Use Abstract Classes in a Program</h3>
<p>Let's see how we can use the <code>SavingsAccount</code> and <code>CheckingAccount</code> classes in a <code>Program.cs</code> file.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">namespace</span> <span class="hljs-title">AbstractClasses</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            <span class="hljs-comment">// Create a savings account</span>
            BankAccount savings = <span class="hljs-keyword">new</span> SavingsAccount(<span class="hljs-string">"SA123"</span>, <span class="hljs-number">1000</span>, <span class="hljs-number">1.5</span>m);
            <span class="hljs-comment">// Create a checking account</span>
            BankAccount checking = <span class="hljs-keyword">new</span> CheckingAccount(<span class="hljs-string">"CA123"</span>, <span class="hljs-number">500</span>, <span class="hljs-number">200</span>);

            <span class="hljs-comment">// Deposit and withdraw from the savings account</span>
            savings.DisplayAccountInfo();

           <span class="hljs-comment">// Deposit and withdraw from the checking account</span>
            savings.Deposit(<span class="hljs-number">200</span>);

            savings.Withdraw(<span class="hljs-number">100</span>);
            <span class="hljs-comment">// Display the updated account information</span>
            savings.DisplayAccountInfo();

            checking.DisplayAccountInfo();

             <span class="hljs-comment">// Deposit and withdraw from the checking account</span>
            checking.Deposit(<span class="hljs-number">300</span>);

            checking.Withdraw(<span class="hljs-number">600</span>);

            <span class="hljs-comment">// Display the updated account information</span>
            checking.DisplayAccountInfo();

            <span class="hljs-keyword">try</span>
            {
                checking.Withdraw(<span class="hljs-number">200</span>);
            }
            <span class="hljs-keyword">catch</span> (InvalidOperationException ex)
            {
                Console.WriteLine(<span class="hljs-string">$"Error: <span class="hljs-subst">{ex.Message}</span>"</span>);
            }

            checking.DisplayAccountInfo();
        }
    }
}
</code></pre>
<p>This program will produce the following output:</p>
<pre><code class="lang-markdown">Savings Account SA123 - Balance: 1000, Interest Rate: 1.5%
Deposited 200 to Savings Account SA123. New Balance: 1200
Withdrew 100 from Savings Account SA123. New Balance: 1100
Savings Account SA123 - Balance: 1100, Interest Rate: 1.5%
Checking Account CA123 - Balance: 500, Overdraft Limit: 200
Deposited 300 to Checking Account CA123. New Balance: 800
Withdrew 600 from Checking Account CA123. New Balance: 200
Checking Account CA123 - Balance: 200, Overdraft Limit: 200
Withdrew 200 from Checking Account CA123. New Balance: 0
Checking Account CA123 - Balance: 0, Overdraft Limit: 200
</code></pre>
<p>In this example, the <code>SavingsAccount</code> and <code>CheckingAccount</code> objects are created, and the abstract methods <code>Deposit</code>, <code>Withdraw</code>, and <code>DisplayAccountInfo</code> are called. The abstract class <code>BankAccount</code> ensures that both account types have these methods, while the derived classes provide the specific functionality.</p>
<h3 id="heading-key-points-to-remember-about-abstract-classes">Key Points to Remember About Abstract Classes</h3>
<ul>
<li><p><strong>Cannot be instantiated</strong>: You can't create an instance of an abstract class directly. A subclass must inherit it and provide the implementations for the abstract methods.</p>
</li>
<li><p><strong>Contain abstract methods</strong>: Abstract methods in an abstract class have no body. Any non-abstract class that inherits from the abstract class must implement these methods.</p>
</li>
<li><p><strong>Define common interfaces</strong>: Abstract classes set a common interface for related classes, ensuring they are consistent while allowing different implementations.</p>
</li>
</ul>
<p>Abstract classes are important in C#. They help enforce a structure across related classes but still allow for specific details. By using abstract classes, you can make your code more organized, easier to maintain, and extend.</p>
<h2 id="heading-singleton-classes-in-c-sharp">Singleton Classes in C Sharp</h2>
<p>Singleton classes are a design pattern that restricts the instantiation of a class to one single instance. This is particularly useful when you need a single, shared resource across your application, such as a configuration manager, logging service, or database connection.</p>
<h3 id="heading-why-use-singleton-classes-in-c">Why Use Singleton Classes in C#?</h3>
<p>Imagine you have a class responsible for managing a database connection. You don’t want multiple instances of this class running around, potentially causing issues with resource management or inconsistent data. A Singleton class ensures that only one instance is created and provides a global point of access to it.</p>
<h3 id="heading-example-defining-a-singleton-class">Example: Defining a Singleton Class</h3>
<p>Let’s now see how you can implement a Singleton class in C#:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Define a singleton class</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Singleton</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Singleton instance;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">object</span> lockObject = <span class="hljs-keyword">new</span> <span class="hljs-keyword">object</span>();

    <span class="hljs-comment">// Private constructor prevents instantiation from outside the class</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Singleton</span>(<span class="hljs-params"></span>)</span>
    {
    }

    <span class="hljs-comment">// Public property to access the single instance of the class</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Singleton Instance
    {
        <span class="hljs-keyword">get</span>
        {
            <span class="hljs-comment">// Ensure thread safety</span>
            <span class="hljs-keyword">lock</span> (lockObject)
            {
                <span class="hljs-keyword">if</span> (instance == <span class="hljs-literal">null</span>)
                {
                    instance = <span class="hljs-keyword">new</span> Singleton();
                }
            }
            <span class="hljs-keyword">return</span> instance;
        }
    }

    <span class="hljs-comment">// Example method to demonstrate the singleton instance</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">PrintMessage</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">"Hello, I am a singleton class."</span>);
    }
}
</code></pre>
<p>In this example, the <code>Singleton</code> class is defined with a private constructor, which prevents other classes from creating new instances. The static property <code>Instance</code> returns the single instance of the class, creating it if it doesn't already exist. The <code>lockObject</code> ensures that the class is thread-safe, meaning that even in a multi-threaded environment, only one instance will be created.</p>
<p>The <code>PrintMessage</code> method is just a simple example to show that the Singleton instance can be used like any other class instance.</p>
<h3 id="heading-how-to-use-the-singleton-class-in-programcs">How to Use the Singleton Class in <code>Program.cs</code></h3>
<p>Now let’s see how you can use this Singleton class in your application:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
    {
        <span class="hljs-comment">// Retrieve the single instance of the Singleton class</span>
        Singleton singleton1 = Singleton.Instance;
        singleton1.PrintMessage(); <span class="hljs-comment">// Output: Hello, I am a singleton class.</span>

        <span class="hljs-comment">// Retrieve the instance again</span>
        Singleton singleton2 = Singleton.Instance;

        <span class="hljs-comment">// Check if both instances are the same</span>
        Console.WriteLine(singleton1 == singleton2); <span class="hljs-comment">// Output: True</span>
    }
}
</code></pre>
<p>In this example, we retrieve the Singleton instance twice. Because the class is a Singleton, both <code>singleton1</code> and <code>singleton2</code> refer to the same instance. The <code>==</code> operator confirms this by returning <code>true</code>.</p>
<h3 id="heading-how-to-extend-the-singleton-example">How to Extend the Singleton Example</h3>
<p>You can expand the Singleton pattern to handle more complex scenarios. For example, you could initialize the Singleton instance with configuration data:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ConfigurationManager</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> ConfigurationManager instance;
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-title">Dictionary</span>&lt;<span class="hljs-title">string</span>, <span class="hljs-title">string</span>&gt; settings</span> = <span class="hljs-keyword">new</span> Dictionary&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">string</span>&gt;();

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">ConfigurationManager</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-comment">// Simulate loading settings from a configuration file</span>
        settings[<span class="hljs-string">"AppName"</span>] = <span class="hljs-string">"MyApplication"</span>;
        settings[<span class="hljs-string">"Version"</span>] = <span class="hljs-string">"1.0.0"</span>;
    }

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ConfigurationManager Instance
    {
        <span class="hljs-keyword">get</span>
        {
            <span class="hljs-keyword">if</span> (instance == <span class="hljs-literal">null</span>)
            {
                instance = <span class="hljs-keyword">new</span> ConfigurationManager();
            }
            <span class="hljs-keyword">return</span> instance;
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetSetting</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> key</span>)</span>
    {
        <span class="hljs-keyword">return</span> settings.ContainsKey(key) ? settings[key] : <span class="hljs-literal">null</span>;
    }
}
</code></pre>
<p>Here, <code>ConfigurationManager</code> is a Singleton class that loads and manages application settings. The <code>GetSetting</code> method allows you to retrieve specific configuration values, ensuring that all parts of your application use the same settings.</p>
<h3 id="heading-key-points-to-remember-about-singleton-classes">Key Points to Remember About Singleton Classes</h3>
<ul>
<li><p><strong>Single instance</strong>: Singleton classes ensure that only one instance of the class exists in the application.</p>
</li>
<li><p><strong>Global access</strong>: Singleton provides a global point of access to the instance, making it easy to use across different parts of your application.</p>
</li>
<li><p><strong>Thread safety</strong>: In multi-threaded environments, ensure your Singleton is thread-safe to avoid creating multiple instances.</p>
</li>
<li><p><strong>Use cases</strong>: Common use cases for Singleton include managing configurations, logging services, and database connections.</p>
</li>
</ul>
<p>Singleton classes are a fundamental design pattern in software engineering, offering a simple yet powerful way to manage shared resources. Understanding and correctly implementing Singletons can help you write more efficient and maintainable code.</p>
<h2 id="heading-generic-classes-in-c-sharp">Generic Classes in C Sharp</h2>
<p>Generic classes in C# provide a powerful way to create reusable and type-safe code. By using generic classes, you can design a single class that works with any data type, eliminating the need for type-specific implementations. This makes your code more flexible and reduces redundancy.</p>
<h3 id="heading-why-use-generic-classes">Why Use Generic Classes?</h3>
<p>Imagine you need to implement a stack that stores integers. Later, you might need another stack to store strings.</p>
<p>Instead of writing two separate classes, you can write one generic stack class that can handle both data types—and any others you might need. Generic classes help you avoid code duplication and make your codebase easier to maintain.</p>
<h3 id="heading-example-defining-a-generic-class">Example: Defining a Generic Class</h3>
<p>Let’s take a look at a simple implementation of a generic stack class:</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Define a generic class</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Stack</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">List</span>&lt;<span class="hljs-title">T</span>&gt; items</span> = <span class="hljs-keyword">new</span> List&lt;T&gt;();

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Push</span>(<span class="hljs-params">T item</span>)</span>
    {
        items.Add(item);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">Pop</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">if</span> (items.Count == <span class="hljs-number">0</span>)
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException(<span class="hljs-string">"The stack is empty."</span>);
        }
        T item = items[items.Count - <span class="hljs-number">1</span>];
        items.RemoveAt(items.Count - <span class="hljs-number">1</span>);
        <span class="hljs-keyword">return</span> item;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">Peek</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">if</span> (items.Count == <span class="hljs-number">0</span>)
        {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> InvalidOperationException(<span class="hljs-string">"The stack is empty."</span>);
        }
        <span class="hljs-keyword">return</span> items[items.Count - <span class="hljs-number">1</span>];
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">IsEmpty</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">return</span> items.Count == <span class="hljs-number">0</span>;
    }
}
</code></pre>
<p>In this example, the <code>Stack&lt;T&gt;</code> class is defined with a type parameter <code>T</code>. This type parameter is a placeholder that represents the type of data the stack will store. The class includes methods like <code>Push</code> to add an item to the stack, <code>Pop</code> to remove and return the top item, <code>Peek</code> to view the top item without removing it, and <code>IsEmpty</code> to check if the stack is empty.</p>
<p>Because <code>Stack&lt;T&gt;</code> is generic, you can use it with any data type, whether it's <code>int</code>, <code>string</code>, or even a custom class.</p>
<h3 id="heading-how-to-use-the-stack-class-in-programcs">How to Use the Stack Class in <code>Program.cs</code></h3>
<p>Let’s see how this generic <code>Stack</code> class can be used in a program:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
    {
        <span class="hljs-comment">// Stack for integers</span>
        Stack&lt;<span class="hljs-keyword">int</span>&gt; intStack = <span class="hljs-keyword">new</span> Stack&lt;<span class="hljs-keyword">int</span>&gt;();
        intStack.Push(<span class="hljs-number">10</span>);
        intStack.Push(<span class="hljs-number">20</span>);
        Console.WriteLine(intStack.Pop()); <span class="hljs-comment">// Output: 20</span>
        Console.WriteLine(intStack.Peek()); <span class="hljs-comment">// Output: 10</span>

        <span class="hljs-comment">// Stack for strings</span>
        Stack&lt;<span class="hljs-keyword">string</span>&gt; stringStack = <span class="hljs-keyword">new</span> Stack&lt;<span class="hljs-keyword">string</span>&gt;();
        stringStack.Push(<span class="hljs-string">"Hello"</span>);
        stringStack.Push(<span class="hljs-string">"World"</span>);
        Console.WriteLine(stringStack.Pop()); <span class="hljs-comment">// Output: World</span>
        Console.WriteLine(stringStack.Peek()); <span class="hljs-comment">// Output: Hello</span>
    }
}
</code></pre>
<p>In this example, we create two instances of the <code>Stack</code> class: one that stores integers and another that stores strings. The flexibility of generics allows us to use the same class to work with different data types, making our code more reusable and concise.</p>
<h3 id="heading-how-to-extend-the-generic-class">How to Extend the Generic Class</h3>
<p>Let’s take it a step further and extend our <code>Stack</code> class to include a method that returns all items as an array:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> T[] <span class="hljs-title">ToArray</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">return</span> items.ToArray();
}
</code></pre>
<p>Now, you can easily convert the stack’s items into an array:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">int</span>[] intArray = intStack.ToArray();
<span class="hljs-keyword">string</span>[] stringArray = stringStack.ToArray();
</code></pre>
<p>This extension further showcases the power of generics, allowing the same method to work with different data types seamlessly.</p>
<h3 id="heading-key-points-to-remember-about-generic-classes">Key Points to Remember About Generic Classes</h3>
<ul>
<li><p><strong>Flexibility</strong>: Generic classes can handle any data type, making them adaptable and reusable.</p>
</li>
<li><p><strong>Type safety</strong>: Using type parameters ensures that your code is type-safe, catching errors during compile-time instead of runtime.</p>
</li>
<li><p><strong>Code reuse</strong>: Generics remove the need to duplicate code for different data types, resulting in cleaner and easier-to-maintain code.</p>
</li>
<li><p><strong>Type parameters</strong>: Generic classes use type parameters as placeholders for the actual data types you will use when creating an instance of the class.</p>
</li>
</ul>
<p>Generic classes are crucial in C# for building flexible, reusable, and type-safe code. By learning and using generics, you can create more reliable and maintainable applications.</p>
<h2 id="heading-internal-classes-in-c-sharp">Internal Classes in C Sharp</h2>
<p>Internal classes in C# are a powerful way to encapsulate implementation details within an assembly. By using the <code>internal</code> access modifier, you can restrict access to certain classes, ensuring they are only accessible within the same assembly.</p>
<p>This is particularly useful for hiding complex logic or utility classes that are not intended to be exposed to the public API of your library or application.</p>
<h3 id="heading-why-use-internal-classes">Why Use Internal Classes?</h3>
<p>In a large application, you may have classes that should only be used internally by your code and not by external consumers. For example, helper classes, utility functions, or components of a larger system that do not need to be exposed outside the assembly can be marked as <code>internal</code>. This ensures that your public API remains clean and focused while still allowing full functionality within the assembly.</p>
<h3 id="heading-example-defining-an-internal-class">Example: Defining an Internal Class</h3>
<p>Let’s consider a scenario where you have a library that processes orders. You might have a class that handles the complex logic of calculating discounts, but you don't want this class to be accessible to users of your library. Instead, you only expose the main <code>OrderProcessor</code> class, keeping the discount logic hidden with an internal class.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Define a public class that uses an internal class</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OrderProcessor</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ProcessOrder</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> orderId</span>)</span>
    {
        <span class="hljs-comment">// Internal class is used here</span>
        DiscountCalculator calculator = <span class="hljs-keyword">new</span> DiscountCalculator();
        <span class="hljs-keyword">decimal</span> discount = calculator.CalculateDiscount(orderId);
        Console.WriteLine(<span class="hljs-string">$"Order <span class="hljs-subst">{orderId}</span> processed with a discount of <span class="hljs-subst">{discount:C}</span>"</span>);
    }

    <span class="hljs-comment">// Internal class that handles discount calculations</span>
    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">DiscountCalculator</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> <span class="hljs-title">CalculateDiscount</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> orderId</span>)</span>
        {
            <span class="hljs-comment">// Complex discount calculation logic</span>
            <span class="hljs-keyword">return</span> orderId * <span class="hljs-number">0.05</span>m;
        }
    }
}
</code></pre>
<p>In this example, the <code>DiscountCalculator</code> class is marked as <code>internal</code>, meaning it’s only accessible within the assembly. The <code>OrderProcessor</code> class, which is <code>public</code>, uses this internal class to process orders. External users of the library can call <code>ProcessOrder</code> without needing to know about or interact with the <code>DiscountCalculator</code> class.</p>
<h3 id="heading-how-to-use-the-internal-class-in-programcs">How to Use the Internal Class in <code>Program.cs</code></h3>
<p>Now, let's see how this works in practice:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
    {
        OrderProcessor processor = <span class="hljs-keyword">new</span> OrderProcessor();
        processor.ProcessOrder(<span class="hljs-number">12345</span>); <span class="hljs-comment">// Output: Order 12345 processed with a discount of $617.25</span>
    }
}
</code></pre>
<p>In this example, the <code>ProcessOrder</code> method is publicly accessible, but the internal workings of discount calculation remain hidden, providing a clean and secure API.</p>
<h3 id="heading-key-points-to-remember-about-internal-classes">Key Points to Remember About Internal Classes</h3>
<ul>
<li><p><strong>Limited access</strong>: Internal classes can only be accessed within the same assembly, which helps keep your public API simple and focused.</p>
</li>
<li><p><strong>Encapsulation</strong>: They are used to hide implementation details, like helper functions or complex logic, that shouldn't be publicly visible.</p>
</li>
<li><p><strong>Visibility control</strong>: The <code>internal</code> access modifier lets you control which classes and members are visible, ensuring only the necessary parts of your code are accessible to other assemblies.</p>
</li>
</ul>
<p>Internal classes are important for managing complex applications, allowing you to control what parts of your code can be accessed from outside your assembly. By hiding details and limiting access, you can keep your codebase clean, easy to maintain, and secure.</p>
<h2 id="heading-nested-classes-in-c-sharp">Nested Classes in C Sharp</h2>
<p>Nested classes in C# are defined within another class. This structure is useful for grouping related classes together and encapsulating the implementation details. Nested classes can be either static or non-static, and they have direct access to the private members of their enclosing class.</p>
<h3 id="heading-why-use-nested-classes">Why Use Nested Classes?</h3>
<p>Nested classes are particularly useful when a class is closely tied to the logic of another class and isn’t meant to be used independently. They allow you to encapsulate helper classes, hide them from other parts of the program, and keep related code together. This can lead to a cleaner, more organized codebase.</p>
<h3 id="heading-example-defining-a-nested-class">Example: Defining a Nested Class</h3>
<p>Let’s consider a scenario where we have a class that represents a <code>Car</code> and another class that represents a <code>Engine</code>. Since the <code>Engine</code> class is closely related to the <code>Car</code> class and doesn’t make much sense on its own, we can define it as a nested class within <code>Car</code>.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Define a class with a nested class</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>
{
    <span class="hljs-comment">// Define private fields</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> model;
    <span class="hljs-keyword">private</span> Engine carEngine;

   <span class="hljs-comment">// Constructor</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Car</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> model</span>)</span>
    {
        <span class="hljs-keyword">this</span>.model = model;
        carEngine = <span class="hljs-keyword">new</span> Engine();
    }


    <span class="hljs-comment">// Method to start the car</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">StartCar</span>(<span class="hljs-params"></span>)</span>
    {
        carEngine.StartEngine();
        Console.WriteLine(<span class="hljs-string">$"<span class="hljs-subst">{model}</span> is starting..."</span>);
    }

    <span class="hljs-comment">// Nested class</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Engine</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">StartEngine</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">"Engine started."</span>);
        }
    }
}
</code></pre>
<p>In this example, the <code>Car</code> class has a private field <code>model</code> and a method <code>StartCar</code> that starts the car. The <code>Engine</code> class is nested within the <code>Car</code> class and contains a <code>StartEngine</code> method. By nesting <code>Engine</code> inside <code>Car</code>, we express the close relationship between the two.</p>
<h3 id="heading-how-to-use-the-nested-class-in-programcs">How to Use the Nested Class in <code>Program.cs</code></h3>
<p>Let’s see how we can use the <code>Car</code> class and its nested <code>Engine</code> class in a program:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
    {
        Car myCar = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"Toyota"</span>);
        myCar.StartCar(); <span class="hljs-comment">// Output: Engine started. Toyota is starting...</span>

        <span class="hljs-comment">// Although you can create an instance of the nested class separately, it usually makes sense to use it through the outer class</span>
        Car.Engine engine = <span class="hljs-keyword">new</span> Car.Engine();
        engine.StartEngine(); <span class="hljs-comment">// Output: Engine started.</span>
    }
}
</code></pre>
<p>In this example, we create an instance of the <code>Car</code> class and call the <code>StartCar</code> method, which internally calls the <code>StartEngine</code> method of the nested <code>Engine</code> class. While it's possible to instantiate the nested class separately, it’s more common to access it through the outer class, emphasizing the relationship between the two.</p>
<h3 id="heading-key-points-to-remember-about-nested-classes">Key Points to Remember About Nested Classes</h3>
<ul>
<li><p><strong>Encapsulation</strong>: Nested classes keep details hidden that shouldn't be seen outside the main class.</p>
</li>
<li><p><strong>Access to private members</strong>: Nested classes can access private parts of the main class, making them good for helper classes that need to work with the main class's internal parts.</p>
</li>
<li><p><strong>Organization</strong>: Use nested classes to keep related classes together, which makes the code cleaner and more organized.</p>
</li>
<li><p><strong>Static or non-static</strong>: Nested classes can be static or non-static. Static nested classes can't access the instance parts of the main class directly, but non-static nested classes can.</p>
</li>
</ul>
<p>Nested classes are a useful way to organize your code, especially for complex objects with closely related parts. Keeping related classes together makes your code easier to manage and maintain.</p>
<h2 id="heading-partial-classes-in-c-sharp">Partial Classes in C Sharp</h2>
<p>Partial classes in C# allow you to split a class definition across multiple files. This feature is particularly useful in large projects, where it can be beneficial to break a complex class into smaller, more manageable sections.</p>
<p>By using the <code>partial</code> keyword, you can organize your code better, especially when working with generated code or collaborating in a team environment.</p>
<h3 id="heading-why-use-partial-classes">Why Use Partial Classes?</h3>
<p>Imagine you’re working on a large application where a single class contains hundreds of lines of code. This can become difficult to manage and maintain. By using partial classes, you can divide the class into logical parts, each residing in a separate file. This not only makes the code more readable but also allows multiple developers to work on different parts of the class simultaneously without causing merge conflicts.</p>
<h3 id="heading-example-defining-a-partial-class-in-c">Example: Defining a Partial Class in C</h3>
<p>Let’s say we have a class that handles various operations for an employee management system. Instead of putting all methods in one file, we can split them across multiple files using partial classes.</p>
<p><strong>File 1:</strong> <code>PartialClass_Methods1.cs</code></p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Define a partial class</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EmployeeOperations</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddEmployee</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> name</span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Employee <span class="hljs-subst">{name}</span> added."</span>);
    }
}
</code></pre>
<p><strong>File 2:</strong> <code>PartialClass_Methods2.cs</code></p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Define the other part of the partial class</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EmployeeOperations</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">RemoveEmployee</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> name</span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Employee <span class="hljs-subst">{name}</span> removed."</span>);
    }
}
</code></pre>
<p>In these examples, the <code>EmployeeOperations</code> class is split into two files, each containing a part of the class. The first file handles adding employees, while the second file handles removing them.</p>
<h3 id="heading-how-to-use-the-partial-class-in-programcs">How to Use the Partial Class in <code>Program.cs</code></h3>
<p>Now, let’s use the <code>EmployeeOperations</code> class in our <code>Program.cs</code> file:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
    <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
    {
        EmployeeOperations operations = <span class="hljs-keyword">new</span> EmployeeOperations();

        operations.AddEmployee(<span class="hljs-string">"John Doe"</span>);    <span class="hljs-comment">// Output: Employee John Doe added.</span>
        operations.RemoveEmployee(<span class="hljs-string">"John Doe"</span>); <span class="hljs-comment">// Output: Employee John Doe removed.</span>
    }
}
</code></pre>
<p>In this example, the <code>EmployeeOperations</code> class, although defined in multiple files, behaves like a single class. The methods <code>AddEmployee</code> and <code>RemoveEmployee</code> are seamlessly combined, providing a clean and organized way to manage operations.</p>
<h3 id="heading-key-points-to-remember-about-partial-classes">Key Points to Remember About Partial Classes</h3>
<ul>
<li><p><strong>Code organization</strong>: Partial classes help keep large classes organized by splitting them into smaller, focused sections.</p>
</li>
<li><p><strong>Team collaboration</strong>: Multiple developers can work on different parts of the same class without interfering with each other’s code.</p>
</li>
<li><p><strong>Generated code</strong>: Often used with auto-generated code, where part of the class is generated by a tool, and the rest is written manually.</p>
</li>
</ul>
<p>Partial classes are a powerful feature in C# that allows for better code management, especially in large-scale applications. By breaking down a class into logical components, you can maintain clean, readable, and maintainable code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Classes are the building blocks of object-oriented programming in C#. By understanding the different types of classes—abstract, static, sealed, concrete, and singleton—you can create well-structured, maintainable, and efficient code.</p>
<p>Whether you’re designing utility classes, defining abstract interfaces, or encapsulating complex logic, classes play a crucial role in shaping your application’s architecture.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Classes – How They Work with Use Case Example ]]>
                </title>
                <description>
                    <![CDATA[ In this blog post I'll walk you through a real life example which uses the concept of classes in JavaScript.  I think it's helpful to work with a practical use case because it is much simpler to understand the concepts when you can relate them to rea... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-classes-how-they-work-with-use-case/</link>
                <guid isPermaLink="false">66bb5549e326dc37a9d68ee3</guid>
                
                    <category>
                        <![CDATA[ classes ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Keyur Paralkar ]]>
                </dc:creator>
                <pubDate>Mon, 13 Dec 2021 19:24:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/12/feliphe-schiarolli-hes6nUC1MVc-unsplash-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this blog post I'll walk you through a real life example which uses the concept of classes in JavaScript. </p>
<p>I think it's helpful to work with a practical use case because it is much simpler to understand the concepts when you can relate them to real life. </p>
<p>So in this guide, you will learn about classes in JavaScript, inheritance, abstract functions, how to use keywords such as <code>super</code> and <code>extend</code>s, static keywords, and private members of classes.</p>
<p>Let's dive in.</p>
<h2 id="heading-table-of-contents">Table of contents</h2>
<ul>
<li><a class="post-section-overview" href="#Prerequisites">Prerequisites</a></li>
<li><a class="post-section-overview" href="#heading-what-are-classes-in-javascript">What Are Classes in JavaScript?</a></li>
<li><a class="post-section-overview" href="#heading-use-case-description">Use Case Description</a></li>
<li><a class="post-section-overview" href="#heading-abstract-functions-and-inheritance-in-chair-management-system">Abstract Functions and Inheritance in Chair Management System</a></li>
<li><a class="post-section-overview" href="#heading-static-keyword-in-javascript">Static Keyword in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-private-members-of-classes-in-javascript">Private members in JavaScript</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before you start reading this blog post you should have a basic understanding of the following topics:</p>
<ul>
<li><a target="_blank" href="https://drawio-app.com/uml-class-diagrams-in-draw-io/">Class Diagrams: We are going to use them to showcase our example</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/System_context_diagram">Context Diagram and Container Diagrams</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/object-oriented-programming-javascript/">Knowledge of OOPs</a></li>
<li><a target="_blank" href="https://dev.to/lawrence_eagles/understanding-prototypal-inheritance-in-javascript-4f31#chp-2">Introduction to Prototypal Inheritance, and Prototype chaining</a> </li>
<li><a target="_blank" href="https://dev.to/lawrence_eagles/an-easy-guide-to-understanding-constructors-in-javascript-2mf6">Introduction to constructor functions in JS</a></li>
</ul>
<h2 id="heading-what-are-classes-in-javascript">What are classes in JavaScript?</h2>
<p>Classes were introduced in <a target="_blank" href="https://262.ecma-international.org/6.0/">EcmaScript 2015</a> (ES6) to provide a cleaner way to follow object-oriented programming patterns. </p>
<p>JavaScript still follows a prototype-based inheritance model. Classes in JavaScript are syntactic sugar over the prototype-based inheritance model which we use to implement OOP concepts. </p>
<p>Thus the introduction of classes in JS made it easier for developers to build software around OOP concepts. It also brought in similarities to different OOP-based programming languages such as C++ and Java. </p>
<p>Before classes, we used constructor functions to do OOP in JavaScript. Have a look at the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Pen</span>(<span class="hljs-params">name, color, price</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.color = color;
    <span class="hljs-built_in">this</span>.price = price;
}

<span class="hljs-keyword">const</span> pen1 = <span class="hljs-keyword">new</span> Pen(<span class="hljs-string">"Marker"</span>, <span class="hljs-string">"Blue"</span>, <span class="hljs-string">"$3"</span>);
<span class="hljs-built_in">console</span>.log(pen1);
</code></pre>
<p>The above code shows a <code>Pen</code> constructor function that has name, color, and price properties. We are using the <code>new</code> keyword with the <code>Pen</code> constructor to create an object <code>pen1</code>.  </p>
<p>Now let's say we want to add a new function to the <code>Pen</code> constructor. To do this we need to add the function into the prototype property of <code>Pen</code>. Have a look at the <code>showPrice</code> function below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Pen</span>(<span class="hljs-params">name, color, price</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.color = color;
    <span class="hljs-built_in">this</span>.price = price;
}

<span class="hljs-keyword">const</span> pen1 = <span class="hljs-keyword">new</span> Pen(<span class="hljs-string">"Marker"</span>, <span class="hljs-string">"Blue"</span>, <span class="hljs-string">"$3"</span>);

Pen.prototype.showPrice = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Price of <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.price}</span>`</span>);
}

pen1.showPrice();
</code></pre>
<p>If these concepts aren't making sense to you, then I would recommend brushing up on your JS/background knowledge through the articles mentioned in the Prerequisites section. In particular, check out the article about Prototype and Constructor functions.</p>
<p>Looking at the above code, we can say that we have done what we wanted to do – that is, add a <code>showPrice</code> function to the constructor <code>Pen</code>. But you can see that it's not that readable compared to OOP concepts we implement in C++ or Java.</p>
<p>We can re-create the above example with the help of the <code>class</code> keyword. Have a look at the below code:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Pen</span> </span>{
    <span class="hljs-keyword">constructor</span>(name, color, price){
        <span class="hljs-built_in">this</span>.name = name;
        <span class="hljs-built_in">this</span>.color = color; 
        <span class="hljs-built_in">this</span>.price = price;
    }

    showPrice(){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Price of <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.price}</span>`</span>);
    }
}

<span class="hljs-keyword">const</span> pen1 = <span class="hljs-keyword">new</span> Pen(<span class="hljs-string">"Marker"</span>, <span class="hljs-string">"Blue"</span>, <span class="hljs-string">"$3"</span>);
pen1.showPrice();
</code></pre>
<p>Noticed the difference! We have achieved the same results but with much cleaner syntax. The addition of a new member function like <code>showPrice</code> is much easier as compared to adding a function directly into the constructor's prototype.</p>
<p>Let's dive into classes in JS a bit deeper using an example use case. With this use case, we are going to see how these concepts can be useful to solve some real-life problems.</p>
<h2 id="heading-use-case-description">Use Case Description</h2>
<p><strong>Just a quick note</strong>: the Context, Container, and Classes diagrams drawn in this blog post don't exactly follow the conventions of the above diagrams. I've approximated the diagrams to help you understand the concepts in general.</p>
<p>Before we start, I would suggest reading up on c4models, container diagrams, and context diagrams if you need a refresher. You can find them in the prerequisites section.</p>
<p>We are going to solve the following problem: helping a shopkeeper classify the chairs in their inventory and display them on the screen.</p>
<p>The use case is simple and pretty self-explanatory. Have a look at the diagram below which showcases the overall proposed system:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/js_classes_tut_context.drawio--1-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Context Diagram for the Chair Management System</em></p>
<p>As you can see from the above diagram, there are 3 main components to it:</p>
<ol>
<li><strong>Person:</strong> The shopkeeper is going to interact with our system.</li>
<li><strong>Software System: Stock Interface Portal</strong> - This is an interface that allows the shopkeeper to view or modify the chair information present in the inventory.</li>
<li><strong>Software System: Chair Management System</strong> - This system will allow the interface to fetch or modify the required details requested by the shopkeeper.</li>
</ol>
<p>Now that we understand the use case, let's start with the target system that we are going to focus on in this blog post. It is the <strong>Chair Management System.</strong> </p>
<p>We'll start off by creating some major components in our Chair Management System. Our components in this system are just different classes which will help facilitate the different needs of the shopkeeper.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/chairModel.drawio--2--1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Chair component of Chair Management System</em></p>
<p>Let's add one component called <strong><code>Chair</code></strong>. Since it is a class, it will have its own attributes (properties) and behavior (methods). </p>
<p>Have a look at the above diagram. We can see that:</p>
<ul>
<li>The second row contains attributes of the chair class, for example color, seatHeight, recliningAngle, and so on. </li>
<li>The third row corresponds to the methods that tell us what functions the chair can perform, for example adjustSeatHeight, adjustAngle, moveChair, and so on.</li>
</ul>
<p>We'll follow the above representation for all the components that we'll create throughout this article.</p>
<p>The <code>Chair</code> component will be our base component. This means that all the other types of chairs such as office chairs, dining chairs, and so on will come under this class/component. </p>
<p>Let's start off by creating our base chair class in JS. Have a look at the below code:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chair</span> </span>{
    <span class="hljs-keyword">constructor</span>(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
        <span class="hljs-built_in">this</span>.color = color;
        <span class="hljs-built_in">this</span>.seatHeight = seatHeight;
        <span class="hljs-built_in">this</span>.recliningAngle = recliningAngle;
        <span class="hljs-built_in">this</span>.backSupport = backSupport;
        <span class="hljs-built_in">this</span>.headSupport = headSupport;
        <span class="hljs-built_in">this</span>.padding = padding;
        <span class="hljs-built_in">this</span>.armRests = armRests;
        <span class="hljs-built_in">this</span>.seatSize = seatSize;
        <span class="hljs-built_in">this</span>.isHeightAdjustable = isHeightAdjustable;
        <span class="hljs-built_in">this</span>.isMovable = isMovable;
    }

    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}

<span class="hljs-keyword">const</span> newChair = <span class="hljs-keyword">new</span> Chair(<span class="hljs-string">"Blue"</span>,<span class="hljs-string">"25 inch"</span>,<span class="hljs-string">"20 deg"</span>,<span class="hljs-literal">true</span>,<span class="hljs-literal">false</span>,<span class="hljs-string">"3 inch"</span>,<span class="hljs-literal">true</span>,<span class="hljs-string">"16 inch"</span>,<span class="hljs-literal">false</span>,<span class="hljs-literal">false</span>);

<span class="hljs-built_in">console</span>.dir(<span class="hljs-string">"Chair Prototype"</span>, Chair);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Chair Object"</span>, newChair);
</code></pre>
<p>The chair class has the following members: </p>
<ul>
<li><strong>Attributes</strong>: These will define the attributes of the chair such as color, seat height, backSupport, and so on.</li>
<li><strong>Functions</strong>: These define the behavior of the chair. For example, if the chair has <code>isHeightAdjustable</code> set to true then it can use the function <code>adjustableHeight</code>. You can see that all the functions are declared in the <code>Chair</code> class. These are the abstract functions. We will talk more about these functions later in this article.</li>
</ul>
<p>At the bottom of the code, we have two console log statements. The first one will print out the definition of the class <code>Chair</code> . The second object will print the <code>newChair</code> instance. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/Screenshot-from-2021-12-11-11-58-14.png" alt="Image" width="600" height="400" loading="lazy">
<em>First console.dir output</em></p>
<p>If you look at the first output, it prints out the <code>Chair</code> class. Let's have a look at the contents of it: </p>
<ul>
<li>It consists of a property <code>prototype</code>. This is the prototype that all the instances of class Chair will have.</li>
<li>The <code>name</code> property is the name of the object.</li>
<li>Lastly, we have the <code>__proto__</code>  or <code>[[Prototype]]</code> property. This is the actual prototype of the class <code>Chair</code>.</li>
</ul>
<pre><code class="lang-json">{
    <span class="hljs-attr">"color"</span>: <span class="hljs-string">"Blue"</span>,
    <span class="hljs-attr">"seatHeight"</span>: <span class="hljs-string">"25 inch"</span>,
    <span class="hljs-attr">"recliningAngle"</span>: <span class="hljs-string">"20 deg"</span>,
    <span class="hljs-attr">"backSupport"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"headSupport"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"padding"</span>: <span class="hljs-string">"3 inch"</span>,
    <span class="hljs-attr">"armRests"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"seatSize"</span>: <span class="hljs-string">"16 inch"</span>,
    <span class="hljs-attr">"isHeightAdjustable"</span>: <span class="hljs-literal">false</span>,
    <span class="hljs-attr">"isMovable"</span>: <span class="hljs-literal">false</span>,
    [[Prototype]]: {
        adjustAngle: ƒ adjustAngle()
        adjustableHeight: ƒ adjustableHeight()
        constructor: class Chair
        moveChair: ƒ moveChair()
        [[Prototype]]: Object
    }
}
</code></pre>
<p>The second log statement prints out the information of the chair object instance. It will consist of all of the Chair class attributes. If you notice closely you can see that the prototype of this instance is similar to that of the <code>prototype</code> property of the chair class. This happens because of prototypical inheritance.</p>
<p>Now let's see how we can use this concept by adding a new component/class into our <strong>Chair Management System.</strong></p>
<h2 id="heading-abstract-functions-and-inheritance-in-chair-management-system">Abstract Functions and Inheritance in Chair Management System</h2>
<p>The abstract function is just a function signature in a class without any implementation. It helps us generalize the code so that the subclasses can use them and add their own implementation to it. </p>
<p>To demonstrate this in our use case, let's add one more component to our <strong>Chair Management System.</strong> </p>
<p>I have modified the chair class so that it now consists of defaults. These defaults will be used by all the instances. Later the subclass can modify it. We will see shortly how we can achieve this. Have a look at the new <code>Chair</code> class below:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chair</span> </span>{
    <span class="hljs-keyword">constructor</span>(color, seatHeight, recliningAngle, backSupport, headSupport, padding, armRests, seatSize, isHeightAdjustable, isMovable){
        <span class="hljs-comment">//Defaults which can be changed by the subclass class.</span>
        <span class="hljs-built_in">this</span>.color = color;
        <span class="hljs-built_in">this</span>.seatHeight = seatHeight;
        <span class="hljs-built_in">this</span>.recliningAngle = recliningAngle;
        <span class="hljs-built_in">this</span>.backSupport = <span class="hljs-literal">true</span>;
        <span class="hljs-built_in">this</span>.headSupport = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.padding = <span class="hljs-string">"3 inch"</span>;
        <span class="hljs-built_in">this</span>.armRests = <span class="hljs-literal">true</span>;
        <span class="hljs-built_in">this</span>.seatSize = <span class="hljs-string">"16 inch"</span>;
        <span class="hljs-built_in">this</span>.isHeightAdjustable = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.isMovable = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.type = <span class="hljs-string">"Chair"</span>;
    }

    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}

<span class="hljs-keyword">const</span> newChair = <span class="hljs-keyword">new</span> Chair();

newChair;
</code></pre>
<p>Now let's add a new component/class called <strong><code>OfficeChair</code></strong>. This will inherit the attributes and methods from the <code>Chair</code> class. The new modified class diagram will look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/chairModel.drawio--1---1-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Class diagram</em></p>
<p>Notice that the new class <code>OfficeChair</code> consists of only the methods and not the attributes. We assume here that all the attributes will be inherited from the <code>Chair</code> class.  </p>
<p>For the <code>OfficeChair</code> class, we have implemented the abstract methods present in the <code>Chair</code> class. </p>
<p>Have a look at the below code for the <code>OfficeChair</code> class:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OfficeChair</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Chair</span></span>{
    <span class="hljs-keyword">constructor</span>(color, isHeightAdjustable, seatHeight, recliningAngle){
        <span class="hljs-built_in">super</span>();
        <span class="hljs-built_in">this</span>.type = <span class="hljs-string">"Office Chair"</span>;
        <span class="hljs-built_in">this</span>.color = color;
        <span class="hljs-built_in">this</span>.isHeightAdjustable = isHeightAdjustable;
        <span class="hljs-built_in">this</span>.seatHeight = seatHeight;
        <span class="hljs-built_in">this</span>.recliningAngle = recliningAngle;
        <span class="hljs-built_in">this</span>.isMovable = <span class="hljs-literal">true</span>;
    }

    adjustableHeight(height){
        <span class="hljs-keyword">if</span>(height &gt; <span class="hljs-built_in">this</span>.seatHeight){
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Chair height changed to <span class="hljs-subst">${height}</span>`</span>);        
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Height cannot be decreased more than the seat height <span class="hljs-subst">${<span class="hljs-built_in">this</span>.seatHeight}</span>`</span>);
        }
    }

    adjustAngle(angle){
        <span class="hljs-keyword">if</span>(angle &gt;= <span class="hljs-built_in">this</span>.recliningAngle){
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Chair angle changed to <span class="hljs-subst">${angle}</span>`</span>);        
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Angle cannot be decreased more than the min reclining angle <span class="hljs-subst">${<span class="hljs-built_in">this</span>.recliningAngle}</span>`</span>);
        }
    }

    moveChair(x,y){
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Chair moved to co-ordinates = (<span class="hljs-subst">${x}</span>, <span class="hljs-subst">${y}</span>)`</span>);
    }
}

<span class="hljs-keyword">const</span> newOfficeChair = <span class="hljs-keyword">new</span> OfficeChair(<span class="hljs-string">"Red"</span>, <span class="hljs-literal">true</span>, <span class="hljs-number">30</span>, <span class="hljs-number">30</span>);

<span class="hljs-built_in">console</span>.log(newOfficeChair.adjustableHeight(<span class="hljs-number">31</span>));
<span class="hljs-built_in">console</span>.log(newOfficeChair.adjustAngle(<span class="hljs-number">40</span>));
<span class="hljs-built_in">console</span>.log(newOfficeChair.moveChair(<span class="hljs-number">10</span>,<span class="hljs-number">20</span>));
</code></pre>
<p>This is a class that inherits the functions and attributes from the superclass <code>chair</code>. It uses the <code>extends</code> keyword to allow the <code>OfficeChair</code> class to perform inheritance. </p>
<p>The <code>extends</code> keyword has the following syntax:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ParentClass</span></span>{...}
</code></pre>
<p>Next, we have a constructor function and the implementation of some of the functions from the superclass. Notice that we are using the <code>super</code> keyword in the constructor.</p>
<p>We use the <code>super</code> keyword to call the constructor of the parent class. We can also use it to call functions and properties of the parent class. </p>
<p>A word of caution when you're using the <code>super</code> keyword:</p>
<ul>
<li>Make sure you call the <code>super</code> function at the start of the constructor. If you don't, and you try to access the parent class's properties before you use <code>super</code> in the child class constructor, it will throw an error. </li>
<li>Once the <code>super</code> function is called, then you can access all the attributes and functions of the parent class. </li>
<li>Super is not just related to the classes – you can also use it to call functions on the object's parent. </li>
</ul>
<p>You can read more about <code>super</code> in the MDN <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super">docs</a>.</p>
<p>Lastly, if you notice, we have added the implementation for the abstract functions. The functions are as follows:</p>
<ul>
<li><code>adjustableHeight</code>: This function will check if the input height is greater than the minimum height of the chair. If yes, we can change the height or else display the error message. A person can also increase or decrease the height of the chair. Note that <code>this.seatHeight</code> is the minimum height of the chair from the ground below which the person cannot lower the height.</li>
<li><code>adjustAngle</code>: This function will check if the input angle is greater than the default value <code>this.recliningAngle</code>. If the input angle is greater than the default angle, then the angle will change or else an error message will be displayed.</li>
<li><code>moveChair</code>: Any chair whose <code>isMovable</code> property is true then the corresponding class will have an implementation of the <code>moveChair</code> function. It simply helps to move the chair based on the input x and y coordinates.</li>
</ul>
<p>Note that we have also reinitialized some of the attributes of the <code>Chair</code> class such as <code>type</code>. We will be explicitly defining the <code>type</code> attribute for each subclass. This will help us classify the chairs present in the inventory by assigning these classes to each of them.</p>
<p>You should now have an idea of what abstract functions are and how useful they can be. Some advantages of having abstract functions:</p>
<ul>
<li>Reduces redundancy in the codebase.</li>
<li>Provides a proper way of generalizing classes.</li>
<li>Allows flexibility for subclasses to implement whichever abstract function they need.</li>
</ul>
<h2 id="heading-static-keyword-in-javascript">Static Keyword in Javascript</h2>
<p>The <code>static</code> keyword in JavaScript helps you define functions and properties in the class that cannot be called by the instance of the object. They can only be called by the class itself which consists of these static functions and properties.</p>
<p>Generally, we use <code>static</code> methods in the classes for utility purposes such as printing out all the properties of the class, creating a new object, clearing other objects of the classes, and so on.  </p>
<p>The advantage of using <code>static</code> functions or properties in a class is that:</p>
<ul>
<li>They can be used to create functions/properties which need not be present in the instances. This helps to maintain some isolation in the codebase.</li>
<li>They reduce code redundancy in some cases.</li>
</ul>
<p>Now let's have a look at how we can implement this concept in our <code>Chair</code> class. We will also take a look at some use cases where we can use the <code>static</code> keyword.</p>
<p>Here are the scenarios where you can use the <code>static</code> keyword:</p>
<ul>
<li>Usage in classes</li>
<li>Static within static</li>
<li>Calling static from a constructor</li>
<li>Class static initialization blocks</li>
</ul>
<p>For more information on the above scenarios, please visit the MDN <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static">docs</a>.</p>
<p>We are going to see all the variants of the <code>Chair</code> class via these scenarios:</p>
<h3 id="heading-how-to-use-the-static-keyword-in-classes">How to use the <code>static</code> keyword in classes</h3>
<p>Like any other programming language, this is one of the most beginner-friendly ways to use the static keyword. Let's define some methods and properties of the classes as <code>static</code> and observe the behavior. </p>
<p>Have a look at the below code:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chair</span> </span>{
<span class="hljs-comment">//Defaults that will be common for all the instances:</span>
    <span class="hljs-keyword">static</span> backSupport = <span class="hljs-literal">true</span>;
    <span class="hljs-keyword">static</span> armRests = <span class="hljs-literal">true</span>;

    <span class="hljs-keyword">constructor</span>(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        <span class="hljs-comment">//Defaults which can be changed by the subclass class.</span>
        <span class="hljs-built_in">this</span>.color = color;
        <span class="hljs-built_in">this</span>.seatHeight = seatHeight;
        <span class="hljs-built_in">this</span>.recliningAngle = recliningAngle;
        <span class="hljs-built_in">this</span>.headSupport = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.padding = <span class="hljs-string">"3 inch"</span>;
        <span class="hljs-built_in">this</span>.seatSize = <span class="hljs-string">"16 inch"</span>;
        <span class="hljs-built_in">this</span>.isHeightAdjustable = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.isMovable = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.type = <span class="hljs-string">"Chair"</span>;
    } 

    <span class="hljs-keyword">static</span> logObjectProps(){
        <span class="hljs-built_in">console</span>.dir(<span class="hljs-built_in">this</span>);
    }

    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
</code></pre>
<p>Below is the output of the above code:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/Screenshot-from-2021-12-01-11-05-15.png" alt="Image" width="600" height="400" loading="lazy">
<em>Static variables</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/Screenshot-from-2021-12-01-11-06-35.png" alt="Image" width="600" height="400" loading="lazy">
<em>The output of the static function</em></p>
<p>As you can see above, the static methods are only accessible via the class itself. It cannot be accessed by instances of the <code>Chair</code> class. Instances of the class do not have the static attributes present:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/Screenshot-from-2021-12-01-11-09-20.png" alt="Image" width="600" height="400" loading="lazy">
<em>No static members in instances</em></p>
<p>As you can see above, the instance <code>x</code> of the <code>Chair</code> class does not have the static method or properties present in its definitions. </p>
<p>If you try to access a static method or a property using a class instance then it will throw a reference error or simply return undefined.</p>
<h3 id="heading-how-to-use-the-static-keyword-within-another-static-function">How to use the <code>static</code> keyword within another static function</h3>
<p>There can be a situation where you might need to use the static properties or function inside another static function. You can do this by referring to your other property/function using this keyword inside the static function. </p>
<p>Let's modify our <code>Chair</code> class to show how this works:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chair</span> </span>{
<span class="hljs-comment">//Defaults that will be common for all the instances:</span>
    <span class="hljs-keyword">static</span> backSupport = <span class="hljs-literal">true</span>;
    <span class="hljs-keyword">static</span> armRests = <span class="hljs-literal">true</span>;

    <span class="hljs-keyword">constructor</span>(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        <span class="hljs-comment">//Defaults which can be changed by the subclass class.</span>
        <span class="hljs-built_in">this</span>.color = color;
        <span class="hljs-built_in">this</span>.seatHeight = seatHeight;
        <span class="hljs-built_in">this</span>.recliningAngle = recliningAngle;
        <span class="hljs-built_in">this</span>.headSupport = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.padding = <span class="hljs-string">"3 inch"</span>;
        <span class="hljs-built_in">this</span>.seatSize = <span class="hljs-string">"16 inch"</span>;
        <span class="hljs-built_in">this</span>.isHeightAdjustable = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.isMovable = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.type = <span class="hljs-string">"Chair"</span>;
    } 

    <span class="hljs-keyword">static</span> logObjectProps(){
        <span class="hljs-built_in">console</span>.dir(<span class="hljs-built_in">this</span>);
    }

        <span class="hljs-comment">//Static within static usage</span>
        <span class="hljs-keyword">static</span> printDefaultProps(){
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Chair Back Support = <span class="hljs-subst">${<span class="hljs-built_in">this</span>.backSupport}</span>`</span>);
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Arm rests support = <span class="hljs-subst">${<span class="hljs-built_in">this</span>.armRests}</span>`</span>);
        }

    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/Screenshot-from-2021-12-05-16-49-12.png" alt="Image" width="600" height="400" loading="lazy">
<em>Output of the above code</em></p>
<p>As you can see the <code>printDefaultProps</code> function has access to the static properties <code>backSupport</code> and <code>armRests</code>.</p>
<h3 id="heading-how-to-call-static-propertiesfunctions-from-a-constructor">How to call static properties/functions from a constructor</h3>
<p>Similar to what we saw above, you can also access these static properties/functions in a constructor. To do this, things are a bit different over here.</p>
<p>Within a constructor to call a static property/function you need to use the <code>&lt;classname&gt;.property</code> or <code>&lt;classname&gt;.functionName()</code>. This happens because the <code>this</code> keyword does not have direct access to the static members. This is not only true for constructors but any non-static functions.</p>
<p>Let's try to understand this by modifying the <code>Chair</code> class.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chair</span> </span>{
<span class="hljs-comment">//Defaults that will be common for all the instances:</span>
    <span class="hljs-keyword">static</span> backSupport = <span class="hljs-literal">true</span>;
    <span class="hljs-keyword">static</span> armRests = <span class="hljs-literal">true</span>;

    <span class="hljs-keyword">constructor</span>(color, seatHeight, recliningAngle, headSupport, padding, seatSize, isHeightAdjustable, isMovable){
        <span class="hljs-comment">//Defaults which can be changed by the subclass class.</span>
        <span class="hljs-built_in">this</span>.color = color;
        <span class="hljs-built_in">this</span>.seatHeight = seatHeight;
        <span class="hljs-built_in">this</span>.recliningAngle = recliningAngle;
        <span class="hljs-built_in">this</span>.headSupport = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.padding = <span class="hljs-string">"3 inch"</span>;
        <span class="hljs-built_in">this</span>.seatSize = <span class="hljs-string">"16 inch"</span>;
        <span class="hljs-built_in">this</span>.isHeightAdjustable = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.isMovable = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.type = <span class="hljs-string">"Chair"</span>;
        <span class="hljs-built_in">console</span>.log(Chair.printDefaultProps()); <span class="hljs-comment">//Usage of static method inside constructor</span>
    } 

    <span class="hljs-keyword">static</span> logObjectProps(){
        <span class="hljs-built_in">console</span>.dir(<span class="hljs-built_in">this</span>);
    }

        <span class="hljs-comment">//Static within static usage</span>
        <span class="hljs-keyword">static</span> printDefaultProps(){
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Chair Back Support = <span class="hljs-subst">${<span class="hljs-built_in">this</span>.backSupport}</span>`</span>);
                <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Arm rests support = <span class="hljs-subst">${<span class="hljs-built_in">this</span>.armRests}</span>`</span>);
        }

    adjustableHeight() {};
    adjustAngle(){};
    moveChair(){};    
}
</code></pre>
<p>In the above code, the last line <code>console.log(Chair.printDefaultProps());</code> showcases how we can use a static method inside a constructor.</p>
<h2 id="heading-private-members-of-classes-in-javascript">Private members of classes in Javascript</h2>
<p>Private members are members of the class which can only be used internally by the class itself. They cannot be accessed outside the class. Even the instances of the class cannot access these private members. </p>
<p>All private members are declared using <code>#&lt;propertName&gt;</code> syntax. They are generally called <em>hash names</em>. </p>
<p>Let's have a look at an example based on our use case. </p>
<p>We'll define some new properties inside the <code>OfficeChair</code> class. Suppose we want to add default billing information for all the office chairs. We also want these to be only accessible to the <code>OfficeChair</code> class so that the other utility functions can use these variables. </p>
<p>We don't want other classes to interfere with the billing information of other classes. To handle this we can use private fields.</p>
<p>Consider the addition of the following fields:</p>
<ul>
<li>Price</li>
<li>Maximum Discount</li>
<li>Seller Address</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/chairModel2.drawio--1-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Updated Class Diagram</em></p>
<p>Note that we can represent private fields in a class diagram using a dash, like this: <code>-</code>.</p>
<p>Have a look at the code below which demonstrates how we have added these fields into the class <code>OfficeChair</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">OfficeChair</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Chair</span> </span>{
    <span class="hljs-comment">//Newly Added Properties</span>
    #basePrice;
    #maxDiscount;
    #sellerAddress;

    <span class="hljs-keyword">constructor</span>(type, color, isHeightAdjustable, seatHeight, recliningAngle) {
        <span class="hljs-built_in">super</span>();
        <span class="hljs-built_in">this</span>.type = type;
        <span class="hljs-built_in">this</span>.color = color;
        <span class="hljs-built_in">this</span>.isHeightAdjustable = isHeightAdjustable;
        <span class="hljs-built_in">this</span>.seatHeight = seatHeight;
        <span class="hljs-built_in">this</span>.recliningAngle = recliningAngle;
        <span class="hljs-built_in">this</span>.isMovable = <span class="hljs-literal">true</span>;
        <span class="hljs-built_in">this</span>.#basePrice = <span class="hljs-number">1000</span>;
        <span class="hljs-built_in">this</span>.#maxDiscount = <span class="hljs-number">5</span>; <span class="hljs-comment">//In percentage</span>
        <span class="hljs-built_in">this</span>.#sellerAddress = <span class="hljs-string">"XYZ, street"</span>;
    }

    adjustableHeight(height) {
        <span class="hljs-keyword">if</span> (height &gt; <span class="hljs-built_in">this</span>.seatHeight) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Chair height changed to <span class="hljs-subst">${height}</span>`</span>);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Height cannot be decreased more than the seat height <span class="hljs-subst">${<span class="hljs-built_in">this</span>.seatHeight}</span>`</span>);
        }
    }

    adjustAngle(angle) {
        <span class="hljs-keyword">if</span> (angle &gt;= <span class="hljs-built_in">this</span>.recliningAngle) {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Chair angle changed to <span class="hljs-subst">${angle}</span>`</span>);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Angle cannot be decreased more than the min reclining angle <span class="hljs-subst">${<span class="hljs-built_in">this</span>.recliningAngle}</span>`</span>);
        }
    }

    moveChair(x, y) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Chair moved to co-ordinates = (<span class="hljs-subst">${x}</span>, <span class="hljs-subst">${y}</span>)`</span>);
    }

    <span class="hljs-comment">//Newly Added function</span>
    #getChairAmount(taxCharge) {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.#basePrice + (<span class="hljs-built_in">this</span>.#basePrice - <span class="hljs-built_in">this</span>.#basePrice * <span class="hljs-built_in">this</span>.#maxDiscount / <span class="hljs-number">100</span>) + taxCharge;
    }

    <span class="hljs-comment">//Newly Added function</span>
    generateBill() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"**** BILLING INFORMATION ****"</span>);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Chair Price = <span class="hljs-subst">${<span class="hljs-built_in">this</span>.#getChairAmount(<span class="hljs-number">20</span>)}</span>`</span>);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Seller Address = <span class="hljs-subst">${<span class="hljs-built_in">this</span>.#sellerAddress}</span>`</span>);
    }
}
</code></pre>
<p>When you run the above code in the console, you should see the following output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/12/Screenshot-from-2021-12-05-17-03-53.png" alt="Image" width="600" height="400" loading="lazy">
<em>Output of private members</em></p>
<p>As you can see from the above output, we have executed the <code>generateBill</code> function. This function accesses the private fields and function within the class to generate the billing information. </p>
<p>These private variables will only be accessible within the class itself. If you try to reference any of the private members of the class then it will throw a syntax error like below:</p>
<pre><code class="lang-javascript">Uncaught <span class="hljs-built_in">SyntaxError</span>: Private field <span class="hljs-string">'#basePrice'</span> must be declared <span class="hljs-keyword">in</span> an enclosing <span class="hljs-class"><span class="hljs-keyword">class</span></span>
</code></pre>
<p>Let me demonstrate how it will look if a subclass tries to access the private variables of the base class:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DinningChair</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">OfficeChair</span></span>{}

<span class="hljs-keyword">let</span> dineChair = <span class="hljs-keyword">new</span> DinningChair();
dineChair.#basePrice(); <span class="hljs-comment">//Throws syntax error</span>
</code></pre>
<p>The above code will throw a syntax error since you are trying to access the private property of another class.</p>
<p>Static private variables are out of the scope of this blog post, so we won't discuss them further. But you can read about them <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields">here</a>.</p>
<h2 id="heading-summary">Summary</h2>
<p>These are some of the ways we can leverage classes in JavaScript to implement object-oriented programming concepts in a real-world example. </p>
<p>You can read more about advanced object-oriented concepts below:</p>
<ul>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)">Polymorphism</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)">Types of inheritance</a></li>
</ul>
<p>Thank you for reading!</p>
<p>Follow me on <a target="_blank" href="https://twitter.com/keurplkar">Twitter</a>, <a target="_blank" href="http://github.com/keyurparalkar">GitHub</a>, and <a target="_blank" href="https://www.linkedin.com/in/keyur-paralkar-494415107/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Excel Classes Online – 11 Free Excel Training Courses ]]>
                </title>
                <description>
                    <![CDATA[ Spreadsheet software like Microsoft Excel is used by everyone from office workers to data scientists. Excel gives a lot of power to people working with data, but it can also be intimidating. We've released a full course on the freeCodeCamp.org YouTub... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/excel-classes-online-free-excel-training-courses/</link>
                <guid isPermaLink="false">66c34a054f7405e6476b01a7</guid>
                
                    <category>
                        <![CDATA[ classes ]]>
                    </category>
                
                    <category>
                        <![CDATA[ excel ]]>
                    </category>
                
                    <category>
                        <![CDATA[ online courses ]]>
                    </category>
                
                    <category>
                        <![CDATA[ training ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tutorial ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 15 Mar 2021 22:21:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/03/excel.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Spreadsheet software like Microsoft Excel is used by everyone from office workers to data scientists. Excel gives a lot of power to people working with data, but it can also be intimidating.</p>
<p>We've released a full course on the freeCodeCamp.org YouTube channel that will teach you how to use Microsoft Excel from the beginning. You will learn by creating 6 real-world projects. Most of the content applies to Google Sheets as well.</p>
<p>The course was created by Shad Sluiter. Shad is a professor of computer science at Grand Canyon University. Over the past 20 years he has taught students from grade 6 to senior citizens in many aspects of technology.</p>
<p>Excel is one of the most used tools in business, engineering, accountancy and many more industries. It helps you organize and manipulate a large amount of data which can be otherwise time-consuming, mundane, and difficult to organize.</p>
<p>If you are in the business sector, learning Excel is a necessity. It helps you manage inventory, human resources, and finances.</p>
<p>In this Excel course, you will learn how to:</p>
<ul>
<li>enter data,</li>
<li>navigate through a spreadsheet,</li>
<li>create formulas to solve problems,</li>
<li>create charts and graphs,</li>
<li>understand relative vs absolute references,</li>
<li>import and export data,</li>
<li>implement VLOOKUP,</li>
<li>use pivot tables,</li>
<li>split and concatenate text,</li>
<li>and more.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/image-12.png" alt="Image" width="600" height="400" loading="lazy">
<em>Source: [xkcd](https://xkcd.com/1906/" style="box-sizing: inherit; margin: 0px; padding: 0px; border: 0px; font-style: inherit; font-variant: inherit; font-weight: inherit; font-stretch: inherit; line-height: inherit; font-family: inherit; font-size: 17.6px; vertical-align: baseline; background-color: transparent; color: var(--gray90); text-decoration: underline; cursor: pointer; word-break: break-word;)</em></p>
<p>While learning Excel, you will create the following six projects:</p>
<ul>
<li>Payroll</li>
<li>Gradebook</li>
<li>Decision Factors</li>
<li>Sales Database</li>
<li>Car Inventory</li>
<li>Problem Solving Templates</li>
</ul>
<h2 id="heading-here-is-the-free-full-length-microsoft-excel-course">Here is the free full-length Microsoft Excel course:</h2>
<p>📺 <a target="_blank" href="https://www.freecodecamp.org/news/learn-microsoft-excel/">Learn Microsoft Excel - Full 3-hour Video Course</a> on YouTube.</p>
<h2 id="heading-free-excel-courses-and-tutorials">Free Excel Courses and Tutorials</h2>
<p>And here are a lot of other free Excel courses and tutorials you can use to master Excel. These answer some of the most widely-asked questions about Excel.</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/word-count-in-excel-how-to-check-the-number-of-words/">Word Count in Excel – How to Check the Number of Words</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-add-numbers-in-excel-with-the-excel-sum-formula/">AutoSum Excel – How to Add Numbers with the Sum Formula</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/auto-numbering-in-excel/">Auto-Numbering in Excel – How to Number Cells Automatically</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/vlookup-in-excel/">VLOOKUP Example – How to Do VLOOKUP in Excel</a></li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/06/excel-1771393_1920.jpg" alt="Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic" width="600" height="400" loading="lazy"></p>
<p>And here are some Excel programming tutorials, if you want to combine Python and other programming languages with spreadsheets to automate even more of your work.</p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-create-read-update-and-search-through-excel-files-using-python-c70680d811d4/">How to create, read, update and search through Excel files using Python</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/excel-vba-tutorial/">Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-remove-duplicates-in-excel-delete-duplicate-rows-with-a-few-clicks/">How to Remove Duplicates in Excel – Delete Duplicate Rows with a Few Clicks</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/auto-updating-excel-python-aws/">How to Create Auto-Updating Excel Spreadsheets of Stock Market Data with Python, AWS, and IEX Cloud</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/stripe-and-node-js-4-best-practices-and-examples/">How to Build an Excellent Stripe Integration with Node.js: 4 Best Practices and Examples</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/generate-excel-report-in-spring-rest-api/">How to Generate an Excel Report in a Spring Boot REST API with Apache POI and Kotlin</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
