<?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[ inheritance - 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[ inheritance - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 17 May 2026 22:28:53 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/inheritance/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What is Prototypal Inheritance in JavaScript? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Prototypal inheritance can feel like a complex concept shrouded in technical jargon. But fear not! This guide will break it down using clear, relatable examples that go beyond the typical textbook explanations.  We'll ditch the confusing terms and fo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-prototypal-inheritance/</link>
                <guid isPermaLink="false">66c375021e62f88108dcb768</guid>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Austin Asoluka ]]>
                </dc:creator>
                <pubDate>Fri, 31 May 2024 08:10:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/Screenshot-2024-05-29-at-00.19.30.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Prototypal inheritance can feel like a complex concept shrouded in technical jargon. But fear not! This guide will break it down using clear, relatable examples that go beyond the typical textbook explanations. </p>
<p>We'll ditch the confusing terms and focus on real-world scenarios that you can easily understand.</p>
<p>By the end of this post, you'll be a prototypal inheritance pro, realizing that it wasn't that hard after all!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-concept-introduction">Concept Introduction</a></li>
<li><a class="post-section-overview" href="#heading-what-are-javascript-objects">What are JavaScript Objects?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-an-object-prototype">What is an Object Prototype?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-prototype-of-a-constructor">How to Work with .prototype Object of a Constructor</a></li>
<li><a class="post-section-overview" href="#heading-how-to-alter-a-constructors-prototype">How to Alter a Constructor's Prototype</a></li>
<li><a class="post-section-overview" href="#heading-the-proto-property">The <strong>proto</strong> Property</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<h2 id="heading-concept-introduction">Concept Introduction</h2>
<p>Imagine that I'm a parent and I have a child and a grandchild. If you were to represent my family tree in a diagram, it should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-09-at-23.12.29.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Fig 1</strong>: Depicting the inheritance structure with family</em></p>
<p>You can see that <code>grandparent</code> is at the top of this family tree, while the <code>parent</code> is a direct descendant of the <code>grandparent</code>, and the <code>child</code> is a descendant of <code>parent</code>.  </p>
<p>If you attempt to walk your way back up, you'll see that <code>grandchild</code> is a child of <code>parent</code> and its own parent is a <code>child</code> of <code>grandparent</code>.</p>
<h2 id="heading-what-are-javascript-objects">What are JavaScript Objects?</h2>
<p>You may have come across this statement at some point: "In JavaScript, almost everything is an Object".</p>
<p>Notice how I spelt <code>Object</code>? When I use Object and object throughout this article, they will mean different things.</p>
<p>Object is a constructor used to create objects. That is: one is parent/ancestor and the other is child.</p>
<p>Using the illustration in <strong>Fig 1.0</strong> above, let's attempt to demonstrate how the family tree works in JavaScript.</p>
<p> <code>Object</code> ⁠ is the grandparent.</p>
<p>Constructors like ⁠ <code>Array</code>, <code>String</code>, <code>Number</code>, <code>Function</code>, ⁠ and <code>⁠ Boolean</code> ⁠ are all descendants of ⁠ <code>Object</code>.</p>
<p>They all produce offspring of different types: <code>array</code>, <code>string</code>, <code>number</code>, <code>function</code>, and <code>Boolean</code>. However, if you trace back to their origin, they are all <code>Objects</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-00.08.57.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Fig 2</strong>: Object is at the top of the inheritance tree in JavaScript</em></p>
<p>So if you're asked why everything (except <code>null</code> and <code>undefined</code>) are regarded as objects in JavaScript, it is because they are all descendants of the <code>Object</code> constructor.  </p>
<p>The constructors listed in the image above are responsible for the different data types you use in JavaScript. That is, they are used behind the scenes to create familiar data types (and you can also use them to create values of different types explicitly).</p>
<p>Let's try out some code snippets.</p>
<h3 id="heading-how-to-create-an-object">How to Create an object</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using the regular object syntax</span>
<span class="hljs-keyword">const</span> newObj = {}

<span class="hljs-comment">// Using the object constructor</span>
<span class="hljs-keyword">const</span> newObjWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>()
</code></pre>
<h3 id="heading-how-to-create-an-array">How to Create an array</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using the regular array syntax</span>
<span class="hljs-keyword">const</span> newArr = []

<span class="hljs-comment">// Using the array constructor</span>
<span class="hljs-keyword">const</span> newArrWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>()
</code></pre>
<h3 id="heading-how-to-create-a-number">How to Create a number</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using the regular syntax</span>
<span class="hljs-keyword">const</span> num = <span class="hljs-number">3</span>

<span class="hljs-comment">// Using the number constructor</span>
<span class="hljs-keyword">const</span> numWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Number</span>(<span class="hljs-number">3</span>)
</code></pre>
<h3 id="heading-how-to-create-a-function">How to Create a function</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using regular function syntax</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logArg</span> (<span class="hljs-params">arg</span>) </span>{
    <span class="hljs-built_in">console</span>.log(arg)
}

<span class="hljs-comment">// Using the Function constructor</span>
<span class="hljs-keyword">const</span> logArgWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Function</span>(<span class="hljs-string">'arg1'</span>, <span class="hljs-string">'console.log(arg1)'</span>)
</code></pre>
<h3 id="heading-how-to-create-a-boolean">How to Create a boolean</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using the regular boolean syntax</span>
<span class="hljs-keyword">const</span> isValid = <span class="hljs-literal">true</span>

<span class="hljs-comment">// Using the Boolean constructor</span>
<span class="hljs-keyword">const</span> isValidWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">true</span>)
</code></pre>
<p>You can see that from the example snippets above, it is possible to explicitly create values using the appropriate constructor, or just by using the simple syntax and allow JavaScript to create the value with the appropriate type for us.</p>
<p><strong>Note</strong>: It is important to state that each method of creating values have their own use case and side effects but we won't be getting into that in this article.</p>
<p>The constructors of these various values have something called a prototype.</p>
<h2 id="heading-what-is-an-object-prototype">What is an Object Prototype?</h2>
<p>In JavaScript, there is something called <code>prototype</code>. The closest concept to this is the human DNA.</p>
<p>Just like DNA acts as blueprints that define characteristics that are passed on through generations of the human family tree, <code>prototypes</code> in JavaScript are used to define properties and methods that are inherited by objects down the JavaScript Object tree.</p>
<p>Let us combine <strong>Fig 1</strong> and <strong>Fig 2</strong> above, updating it now to accommodate the concept of DNA and prototype.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-01.01.47.png" alt="Image" width="600" height="400" loading="lazy">
<em>Fig 3: Comparing JavaScript inheritance with the concept of inheritance in humans</em></p>
<p>In JavaScript, all constructors have a prototype<strong>.</strong> The prototype of a constructor is a dictionary of everything that values created with the constructor should inherit.</p>
<p>Read the line above ☝️ again and proceed when it is clear.</p>
<p>Think of the constructor like a parent and the prototype like the DNA. When the constructor (parent) creates (gives birth to) an offspring (value), the offspring inherits from the DNA (prototype) of it's parent the constructor.</p>
<p>Let's consider another diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-01.28.05.png" alt="Image" width="600" height="400" loading="lazy">
<em>Fig 4: Rough depiction of DNA Inheritance in human</em></p>
<p>From <strong>Fig 4</strong>, you can see that a child inherits directly from their parent and their parent inherits traits from the grandparent. In this chain of inheritance, the child actually inherits from both the grandparent and the parent. </p>
<p>In fact, the child's characteristics traits are strongly influenced by the combination of the DNA of every ancestor before itself.</p>
<p>This is how prototypal inheritance works in JavaScript.</p>
<p>The properties in the prototype of a constructor are inherited by the children created by that constructor. This continues down the chain. You can reason about it like this:</p>
<p>Every descendant in the inheritance chain, inherits everything available in the prototype of its ancestors.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-02.07.22.png" alt="Image" width="600" height="400" loading="lazy">
<em>Fig 5: Prototypal inheritance chain</em></p>
<p>From the diagram above, you can see that all other prototypes inherit from the Object prototype. Therefore, any value created with the Array constructor (for instance), will inherit from the Array prototype, and also, the Object prototype.</p>
<p>This is so because Array prototype inherits from Object prototype.</p>
<p>The term Array prototype is written as <code>Array.prototype</code> in JavaScript, while Object prototype is <code>Object.prototype</code>.</p>
<p><strong>Note</strong>: It is important to note that the concept of DNA is complex so if stretched, we would quickly discover that there are some nuances and difference between how DNA and prototypes work but at the high level, they are very similar.</p>
<p>Therefore, an understanding of inheritance in human family tree would give us a strong understanding of prototypal inheritance in JavaScript.</p>
<p>If you learn better with videos, <a target="_blank" href="https://www.youtube.com/watch?v=TzqJPmEkZ0o">watch this</a>, before you continue.</p>
<h2 id="heading-how-to-work-with-prototype-of-a-constructor">How to Work With <code>.prototype</code> of a Constructor</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-02.16.07.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To view the content of a constructor's prototype, we simply write <code>theConstructorName.prototype</code>. Foe example: <code>Array.prototype</code>, <code>Object.prototype</code>, <code>String.prototype</code> and so on.</p>
<p>Ever imagined how it is possible to write <code>[2, 8, 10].**map**(...)</code>? This is because, in the prototype of the Array constructor, there's a key called <code>map</code>. So even though you did not create the property <code>map</code> by yourself, it was inherited by the array value because that value was created by the <code>Array</code> constructor internally.</p>
<p>Read the above statement thus: Have you ever wondered why you have your specific blood type? It's because you get your blood type from the genes you inherited from your parents!</p>
<p>So the next time you make use of properties and methods like <code>.length</code>, <code>.map</code>, <code>.reduce</code>, <code>.valueOf</code>, <code>.find</code>, <code>.hasOwnProperty</code> on a value, just remember that they are all inherited from the constructor's prototype or some prototype up the prototype chain (the ancestry).</p>
<p>You can see the constructor prototype as the prototype of the entity used to construct/create/make a value.</p>
<p>You should be aware that the <code>.prototype</code> of every constructor is an object. The constructor itself is a function, but it's prototype is an object.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">Array</span>) <span class="hljs-comment">// function</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">Array</span>.prototype) <span class="hljs-comment">// object</span>
</code></pre>
<p><strong>Note</strong>: An exception to this is the prototype of the Function constructor. It is a function object, but it still has properties attached to it and those properties can be accessed like we would do with regular objects (using the <code>.</code> notation).</p>
<p>If you recall, we can add new properties to and retrieve values of already existing properties of objects by using the dot <code>.</code> notation. For example: <code>objectName.propertyName</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"asoluka_tee"</span>,
    <span class="hljs-attr">stack</span>: [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"Node.js"</span>, <span class="hljs-string">"React"</span>, <span class="hljs-string">"MongoDB"</span>],
    <span class="hljs-attr">twitter_url</span>: <span class="hljs-string">"https://twitter.com/asoluka_tee"</span>
}

<span class="hljs-comment">// Using the syntax objectName.propertyName, to access the name key we'll write; user.name </span>
<span class="hljs-keyword">const</span> userName = user.name;
<span class="hljs-built_in">console</span>.log(userName) <span class="hljs-comment">// asoluka_tee</span>

<span class="hljs-comment">// To add a new property to the object we'd write;</span>
user.eyeColor = <span class="hljs-string">"black"</span>

<span class="hljs-comment">// If we log the user object to the console now, we should see eyeColor as part of the object properties with the value of 'black'</span>
</code></pre>
<p>Ever heard of DNA mutation? It's the idea of altering ones DNA. In JavaScript, this is possible with prototypes.</p>
<p>Just like DNA mutation is an extremely dangerous thing to try and the outcome could be uncertain or cause undesired side-effects, altering the prototype of a constructor is not a good idea unless you know what you are doing.</p>
<h2 id="heading-how-to-alter-a-constructors-prototype">How to Alter a Constructor's Prototype</h2>
<p>In JavaScript, it is possible to alter the prototype object of a constructor just the same way you can with a regular JavaScript object (as shown above).  </p>
<p>This time, we just need to follow this syntax <code>constructorName.prototype.newPropertyName = value</code>. For example, if you want to add a new property named <code>currentDate</code> to the prototype object of the Array constructor, you'd write:</p>
<pre><code class="lang-js"><span class="hljs-comment">//constructorName.prototype.newPropertyName</span>
<span class="hljs-built_in">Array</span>.prototype.currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toDateString();
</code></pre>
<p>From now on, in your code, because <code>currentDate</code> now exists in the prototype of the <code>Array</code> constructor <code>(Array.prototype)</code>, every array created in our program can access it like this: <code>[1, 2, 3].currentDate</code> and the result will be today's date.   </p>
<p>If you want every object in your JavaScript program to have access to <code>currentDate</code>, you have to add it to the prototype object of the <code>Object</code> constructor <code>(Object.prototype)</code> instead:</p>
<pre><code class="lang-js"><span class="hljs-comment">//constructorName.prototype.newPropertyName</span>
<span class="hljs-built_in">Object</span>.prototype.currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toDateString();

<span class="hljs-keyword">const</span> newArr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
<span class="hljs-keyword">const</span> newObj = {}
<span class="hljs-keyword">const</span> newBool = <span class="hljs-literal">true</span>

<span class="hljs-comment">// NB: The date shown is the date of writing this article</span>
<span class="hljs-built_in">console</span>.log(newArr.currentDate) <span class="hljs-comment">// 'Fri May 10 2024'</span>
<span class="hljs-built_in">console</span>.log(newObj.currentDate) <span class="hljs-comment">// 'Fri May 10 2024'</span>
<span class="hljs-built_in">console</span>.log(newBool.currentDate) <span class="hljs-comment">// 'Fri May 10 2024'</span>
</code></pre>
<p>This is possible because the prototype object of all constructors inherit from the prototype object of the <code>Object</code> constructor.  </p>
<p>Let's write our version of two popular array methods and use them just like we'd used the original.</p>
<ol>
<li><strong>Array.prototype.reduce</strong>: We'll call ours <code>.reduceV2</code></li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Add our new function to the prototype object of the Array constructor</span>
<span class="hljs-built_in">Array</span>.prototype.reduceV2 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">reducer, initialValue</span>) </span>{
  <span class="hljs-keyword">let</span> accum = initialValue;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    accum = reducer(accum, <span class="hljs-built_in">this</span>[i]);
  }
  <span class="hljs-keyword">return</span> accum;
};

<span class="hljs-comment">// Create an array of scores</span>
<span class="hljs-keyword">let</span> scores = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>];

<span class="hljs-comment">// Use our own version of Array.prototype.reduce to sum the values of the array</span>
<span class="hljs-keyword">const</span> result = scores.reduceV2(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">accum, curr</span>) </span>{
  <span class="hljs-keyword">return</span> accum + curr;
}, <span class="hljs-number">0</span>);

<span class="hljs-comment">// Log the result to the console</span>
<span class="hljs-built_in">console</span>.log(result);
</code></pre>
<p>The focus here is not to explain the whole syntax, it is to show you that by leveraging the prototype chain, you can create your own methods and use them just like the ones JavaScript provides.</p>
<p>Notice that you can just replace our <code>.reduceV2</code> with the original <code>.reduce</code> and it will still work (edge cases are not handled here).  </p>
<ol start="2">
<li><strong>Array.prototype.map</strong>: We'll call ours <code>.mapV2</code> </li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Add mapV2 method to the prototype object of the Array constructor</span>
<span class="hljs-built_in">Array</span>.prototype.mapV2 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">func</span>) </span>{
  <span class="hljs-keyword">let</span> newArray = [];
  <span class="hljs-built_in">this</span>.forEach(<span class="hljs-function">(<span class="hljs-params">item, index</span>) =&gt;</span> newArray.push(func(item, index)));
  <span class="hljs-keyword">return</span> newArray;
};

<span class="hljs-comment">// Create an array of scores </span>
<span class="hljs-keyword">const</span> scores = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Use our mapV2 method to increment every item of the scores array by 2</span>
<span class="hljs-keyword">const</span> scoresTimesTwo = scores.mapV2(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">curr, index</span>) </span>{
    <span class="hljs-keyword">return</span> curr * <span class="hljs-number">2</span>;
})

<span class="hljs-comment">// Log the value of scoresTimesTwo to the console.</span>
<span class="hljs-built_in">console</span>.log(scoresTimesTwo)
</code></pre>
<p><strong>Note</strong>: It is important to state that this is by no means a perfect implementation of the original versions of the <code>map</code> method of JavaScript. It is just an attempt to show you what's possible with a constructor's prototype object.</p>
<p>Before we round up this lesson, there's one more thing I need to mention; It is the <code>__proto__</code> property of every object.</p>
<h2 id="heading-the-proto-property">The <strong>proto</strong> Property</h2>
<p><code>__proto__</code> is a setter and getter for [[prototype]] property of an object. This means that it is used to set or get the prototype of an object (for example, the object from which another object inherits from).</p>
<p>Consider this code snippet;</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {}
<span class="hljs-keyword">const</span> scores = []

user.prototype <span class="hljs-comment">// undefined</span>
scores.prototype <span class="hljs-comment">// undefined</span>
</code></pre>
<p>In the above snippet, we tried to access the prototype object directly from values. This is not possible in JavaScript. </p>
<p>This makes sense because only constructors have the <code>prototype</code> property attached to them.</p>
<p>Just like DNA mutation is risky, it could be chaotic to mess with the prototype object if you do not absolutely know what you're doing.  </p>
<p>Under normal circumstances, a child should not try to alter the DNA of its ancestor or even determine who to inherit traits from 😉</p>
<p>The JavaScript language however provides a way for us to access the prototype object from values that are not constructors using the <code>__proto__</code> property.</p>
<p>This is a deprecated method and should not be used for new projects. I am mentioning <code>__proto__</code> because you could be employed to work in a codebase that still uses it.</p>
<p><code>__proto__</code> allows a value to access the prototype object of it's constructor directly. So if for any reason you wish to see what is available in the prototype chain of a value's immediate ancestor, the <code>__proto__</code> property could be used for that.  </p>
<p>You can also use <code>__proto__</code> to determine which object a value should inherit from.</p>
<p>For instance, we have an object called <code>human</code>, and we want another object called <code>parent</code> to inherit from human, this can be done with the <code>__proto__</code> property of parent like this;</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create a human object</span>
<span class="hljs-keyword">const</span> human = {
    <span class="hljs-attr">walk</span>: <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">'sleeping'</span>) },
    <span class="hljs-attr">talk</span>: <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">'talking'</span>) },
    <span class="hljs-attr">sleep</span>: <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">'sleeping'</span>) }
}

<span class="hljs-comment">// Create a parent object and configure it to inherit from human.</span>
<span class="hljs-keyword">const</span> parent = {
    <span class="hljs-attr">__proto__</span>: human
}

<span class="hljs-comment">// Use a method from the ancestor of parent</span>
parent.sleep() <span class="hljs-comment">// sleeping</span>
</code></pre>
<p>Notice how we can call the <code>sleep</code> method on <code>parent</code> because <code>parent</code> now inherits from <code>human</code>.</p>
<p>There are more modern recommended methods to use when interacting with the prototype object like <code>Object.getPrototypeOf</code> and <code>Object.setPrototypeOf</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {}
<span class="hljs-keyword">const</span> scores = []

<span class="hljs-comment">// Get the prototype of the user object</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(user))

<span class="hljs-comment">// Change the prototype of the scores array. This is like switching ancestry and should be done with great care.</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.setPrototypeOf(scores, {}))

<span class="hljs-comment">// Check the prototype of scores now</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(scores)) <span class="hljs-comment">// {}</span>
</code></pre>
<p>These methods should be used with great care. In fact, you should read more about them in the MDN JS docs to get more information on their pros and cons.</p>
<p>If you've read up to this point, you now know the fundamentals of <code>Array.prototype</code> and from now on, learning about any other concept built on top of this in JavaScript will be easier to understand.  </p>
<p>Let's summarize what you have learned so far.</p>
<h2 id="heading-summary">Summary</h2>
<p>We have different constructors in JavaScript: <code>Array</code>, <code>Boolean</code>, <code>Function</code>, <code>Number</code>, <code>String</code>, and <code>Object</code>.   </p>
<p>Object is the parent of all the other constructors.</p>
<p>Each constructor has a <code>.prototype</code> object and this object contains properties and methods that could be accessed by values created using the constructor. For example, a value created using the <code>Array</code> constructor will have access to all the properties and methods available in the <code>Array.prototype</code> object and this inheritance goes all the way up.  </p>
<p>That is to say, a value created using the <code>Array</code> constructor (whether implicitly or explicitly), will not only have access to properties and methods in the <code>Array.prototype</code> object, but also properties and methods in the <code>Object.prototype</code> object.  </p>
<p>This is because of the concept of prototypal inheritance. <code>Object</code> is parent of <code>Array</code> and every child produced by <code>Array</code> will have access to traits from both <code>Array</code> and <code>Object</code>.</p>
<p>This is what happens when you try to get a property from a value which is not explicitly declared on the value. See code snippet below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {}

<span class="hljs-comment">// trying to retireve .valueOf property from the user object</span>
<span class="hljs-built_in">console</span>.log(user.valueOf)
</code></pre>
<p>Obviously the <code>user</code> object has no <code>.valueOf</code> property, so it looks up its prototype chain for any prototype which has that property and if it is found, the value is returned. Otherwise, we get <code>undefined</code>.</p>
<p>We also learned that we can alter the prototype of any constructor to add functionality and this should be done with caution.</p>
<p>Finally, we learned about how <code>__proto__</code>, <code>getPrototypeOf</code>, and <code>setPrototypeOf</code> could be used to retrieve and set the prototype of a value.</p>
<h3 id="heading-how-is-this-useful">How is This Useful?</h3>
<p>Imagine that you want to create a method which creates a new object based on an array and returns it when called on the array.  </p>
<p>This one's for you to try out yourself.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Array.prototype.toObject</span>
<span class="hljs-keyword">const</span> names = [<span class="hljs-string">'Austin'</span>, <span class="hljs-string">'Tola'</span>, <span class="hljs-string">'Joe'</span>, <span class="hljs-string">'Victor'</span>];

<span class="hljs-comment">// Write your implementation of toObject here.</span>

<span class="hljs-built_in">console</span>.log(names.toObject()) <span class="hljs-comment">// {0: 'Austin', 1: 'Tola', 2: 'Joe', 3: 'Victor'}</span>
</code></pre>
<p>Hurray!!! I know you feel like a JavaScript ninja already.</p>
<p>If you learn better with videos, do subscribe to my <a target="_blank" href="https://www.youtube.com/@asoluka_tee">YouTube</a> channel and I'd be releasing lecture videos soon.</p>
<p>Thanks for reading! Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Virtual Inheritance? ]]>
                </title>
                <description>
                    <![CDATA[ C++ supports the concept of inheritance – that is, a class can inherit properties from other classes.  But sometimes you might need to use what is commonly referred as virtual inheritance.  In this article we will discuss when you might need to use v... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-virtual-inheritance/</link>
                <guid isPermaLink="false">66baef9166a27aea1d2a4019</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abhilekh gautam ]]>
                </dc:creator>
                <pubDate>Thu, 23 Feb 2023 21:09:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/pexels-ruiyang-zhang-3717242.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>C++ supports the concept of inheritance – that is, a class can inherit properties from other classes. </p>
<p>But sometimes you might need to use what is commonly referred as virtual inheritance. </p>
<p>In this article we will discuss when you might need to use virtual inheritance and how to implement it in C++.</p>
<h2 id="heading-what-is-virtual-inheritance">What is Virtual Inheritance?</h2>
<p>In C++, a class can inherit from multiple classes which is commonly referred as multiple inheritance. But this can cause problems sometimes, as you can have multiple instances of the base class.</p>
<p>To tackle this problem, C++ uses a technique which ensures only one instance of a base class is present. That technique is referred as virtual inheritance.</p>
<h3 id="heading-example-of-when-virtual-inheritance-is-useful">Example of When Virtual Inheritance is Useful</h3>
<p>Let's look at an example and then explain what's happening:</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
    <span class="hljs-keyword">public</span>:
     <span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
     <span class="hljs-comment">//some other things</span>
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> :</span> <span class="hljs-keyword">public</span> A { <span class="hljs-comment">// inherit from the Class A.</span>
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">6</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span> :</span> <span class="hljs-keyword">public</span> A { <span class="hljs-comment">// inherit from the Class A.</span>
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">7</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span> :</span> <span class="hljs-keyword">public</span> B, <span class="hljs-keyword">public</span> C { <span class="hljs-comment">// inherit from both class B and C</span>
    <span class="hljs-comment">// something can go here..</span>
};

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    D obj;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>Let's see what's going on here:</p>
<p>First, we have a class <code>A</code> which is being inherited by two classes <code>B</code> and <code>C</code>.  Both of these classes are then inherited by another class <code>D</code>. </p>
<p>Inside our <code>main</code> function, we create a new instance (object) of the class <code>D</code>. We then simply tried to print the value of <code>x</code> to the console. </p>
<p>It might look legit to access the value of <code>x</code> here, because class <code>D</code> is inherited from both <code>B</code> and <code>C</code> which are ultimately inherited from the class <code>A</code>. </p>
<p>But when you try to compile the above program, you get the following error:</p>
<pre><code>&lt;source&gt;: In <span class="hljs-function"><span class="hljs-keyword">function</span> '<span class="hljs-title">int</span> <span class="hljs-title">main</span>(<span class="hljs-params"></span>)':
&lt;<span class="hljs-title">source</span>&gt;:21:22: <span class="hljs-title">error</span>: <span class="hljs-title">request</span> <span class="hljs-title">for</span> <span class="hljs-title">member</span> '<span class="hljs-title">x</span>' <span class="hljs-title">is</span> <span class="hljs-title">ambiguous</span>
   21 |     <span class="hljs-title">std</span>::<span class="hljs-title">cout</span> &lt;&lt; <span class="hljs-title">obj</span>.<span class="hljs-title">x</span> &lt;&lt; <span class="hljs-title">std</span>::<span class="hljs-title">endl</span>;
      |                      ^
&lt;<span class="hljs-title">source</span>&gt;:5:10: <span class="hljs-title">note</span>: <span class="hljs-title">candidates</span> <span class="hljs-title">are</span>: '<span class="hljs-title">int</span> <span class="hljs-title">A</span>::<span class="hljs-title">x</span>'
    5 |      <span class="hljs-title">int</span> <span class="hljs-title">x</span> = 5;
      |          ^
&lt;<span class="hljs-title">source</span>&gt;:5:10: <span class="hljs-title">note</span>:                 '<span class="hljs-title">int</span> <span class="hljs-title">A</span>::<span class="hljs-title">x</span>'</span>
</code></pre><p>The error is pretty clear: <strong><code>error:</code></strong> <code>request for member '</code><strong><code>x</code></strong><code>' is ambiguous</code>. Let's now see how the request is ambiguous. </p>
<p>If we draw the hierarchical class structure, it should become pretty clear:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/hierarchial-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Hierarchical class structure</em></p>
<p>We can see that we have multiple instances of the class <code>A</code>. So the request to the variable <code>x</code> becomes ambiguous because the compiler doesn't know which instance we are referring to – is it through <code>B</code> or through <code>C</code> ? That's the real problem. </p>
<h3 id="heading-one-way-to-solve-this-problem">One Way to Solve this Problem</h3>
<p>One way to tackle the problem is to use the <code>scope-resolution operator (::)</code> with which we can directly specify which instance of <code>A</code> we want.</p>
<pre><code class="lang-c++"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    D obj;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.B::x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.C::x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
}
</code></pre>
<p>Using the  <code>scope-resolution operator</code> we explicitly told the compiler which instance of <code>A</code> we referred to.</p>
<p>The main problem with this approach is that it doesn't solve our problem – because our main problem is having multiple instances of class <code>A</code>, and we still have that. So we need to look around for some other solutions.</p>
<p>And the other solution is to use virtual inheritance. Let's see how it works now.</p>
<h3 id="heading-how-to-use-virtual-inheritance">How to Use Virtual Inheritance</h3>
<p>To inherit virtually we simply add a keyword <code>virtual</code> before our base class name in the derived class declaration like this:</p>
<pre><code class="lang-c++"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">6</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">7</span>;
};
</code></pre>
<p>The addition of the <code>virtual</code> keyword indicates that we want to inherit from <code>A</code> virtually. </p>
<p>Inheriting virtually guarantees that there will be only one instance of the base class among the derived classes that virtually inherited it. After the changes, our hierarchical class structure becomes:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/02/diamond-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Hierarchical structure after virtual inheritance</em></p>
<p>So now if we try to compile the following code, it will successfully compile.</p>
<pre><code class="lang-c++"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span> {</span>
    <span class="hljs-keyword">public</span>:
     <span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">6</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span> :</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">public</span> A{
    <span class="hljs-keyword">public</span>:
      <span class="hljs-keyword">int</span> i = <span class="hljs-number">7</span>;
};
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">D</span> :</span> <span class="hljs-keyword">public</span> B, <span class="hljs-keyword">public</span> C{

};

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
    D obj;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; obj.x &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;

}
</code></pre>
<p>So with the introduction of <code>virtual</code> inheritance we are able to remove the ambiguities we had earlier.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article you learnt about the problem you might face while inheriting a class and a way to solve it using <code>virtual</code> inheritance.</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Inheritance Works in C# – with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Inheritance is a branch of object-oriented programming that helps you write reusable code. It allows you to extend the content of a class to another class.  Other pillars of object-oriented programming include encapsulation, polymorphism, and abstrac... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/inheritance-in-c-sharp/</link>
                <guid isPermaLink="false">66c8c86e58265ae76d481676</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Tue, 29 Nov 2022 20:04:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/caspar-camille-rubin-fPkvU7RDmCo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Inheritance is a branch of object-oriented programming that helps you write reusable code. It allows you to extend the content of a class to another class. </p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/four-pillars-of-object-oriented-programming/">Other pillars of object-oriented programming</a> include encapsulation, polymorphism, and abstraction. </p>
<p>In this article, we will learn about inheritance in C# and the various types of inheritance we have in OOP.</p>
<h2 id="heading-what-is-inheritance">What is Inheritance?</h2>
<p>Inheritance is one of the key features of object-oriented programming (OOP). It is simply the process by which one class (the child or derived class) acquires the properties, methods, and fields of another class (the base, parent, or super class).</p>
<p>Inheritance in object-oriented programming means that you're creating classes that can pass down their properties to other classes without having to explicitly define the properties in new classes. </p>
<p>Inheritance does not only ensure the reusability of the codebase, but it also reduces your code’s complexity.</p>
<h2 id="heading-types-of-inheritance-in-c">Types of Inheritance in C</h2>
<p>Inheritance allows you to build families of related classes. The base/parent class defines the common data for the child class to inherit it. You use the colon operator (:) to show inheritance between two classes.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-comment">//...</span>
    }
    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span>:<span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-comment">//..</span>
    }
}
</code></pre>
<p>There are different types of inheritance in C#. We'll discuss them now.</p>
<h3 id="heading-single-inheritance-in-c">Single Inheritance in C</h3>
<p>Single inheritance usually occurs between two classes – the base class, and the derived class. It occurs when a class is inherited from a single-parent class. </p>
<p>Below is a code sample that shows single inheritance in C#:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id = <span class="hljs-number">9</span>;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayParentClassDetails</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"I am <span class="hljs-subst">{name}</span>"</span>);
            Console.WriteLine(<span class="hljs-string">$"ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getIdFromParentClass</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"This is my ID : <span class="hljs-subst">{Id}</span>"</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">//accessing the inherited members from the child class</span>
            ChildClass child = <span class="hljs-keyword">new</span> ChildClass();
            child.getIdFromParentClass();
        }
    }
}
</code></pre>
<p>In the above code, we derived a subclass (ChildClass) from a super class (ParentClass). The ChildClass now has access to the fields and properties of the ParentClass through inheritance. We could easily access the inherited members from the ChildClass as seen above.</p>
<h3 id="heading-hierarchical-inheritance-in-c">Hierarchical Inheritance in C</h3>
<p>Hierarchical inheritance occurs when more than one derived class is created from a single-parent class.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id = <span class="hljs-number">9</span>;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayParentClassDetails</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"I am <span class="hljs-subst">{name}</span>"</span>);
            Console.WriteLine(<span class="hljs-string">$"ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getIdFromParentClass</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">"Displaying from my Child Class"</span>);
            Console.WriteLine(<span class="hljs-string">$"This is my ID : <span class="hljs-subst">{Id}</span>."</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">AnotherChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getIdFromParentClass</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">"Displaying from my other Child Class"</span>);
            Console.WriteLine(<span class="hljs-string">$"This is my ID : <span class="hljs-subst">{Id}</span>"</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">//accessing the inherited members in the parent class (from the child class)</span>
            ChildClass child = <span class="hljs-keyword">new</span> ChildClass();
            child.getIdFromParentClass();

            <span class="hljs-comment">//accessing the inherited members in the parent class (from the other child class)</span>
            AnotherChildClass anotherChild = <span class="hljs-keyword">new</span> AnotherChildClass();
            anotherChild.getIdFromParentClass();
        }
    }
}
</code></pre>
<p>In the above code, we showed that we can derive more than one child class from a single parent class. </p>
<p>The ChildClass and AnotherChildClass both inherit the fields and methods of the base class, ParentClass. This is called Hierarchical inheritance. The two child classes can therefore access the fields and methods of the parent class.</p>
<h3 id="heading-multi-level-inheritance-in-c">Multi-level Inheritance in C</h3>
<p>Multi-level inheritance occurs when a class is derived from another derived class. It is simply a situation where a derived class is created and used as a base class for another class.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id = <span class="hljs-number">9</span>;

        <span class="hljs-comment">//...</span>
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-comment">//...</span>
        <span class="hljs-comment">//The Child class is the derived class in this case</span>
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ThirdClass</span> : <span class="hljs-title">ChildClass</span>
    {
        <span class="hljs-comment">//...</span>
        <span class="hljs-comment">//The ChildClass is the base class for the ThirdClass</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">//...</span>
        }
    }
}
</code></pre>
<p>In the above code, we also derived a subclass (ChildClass) from a super class (ParentClass). The ChildClass then acts as a base class for a sub-child class which was named ThirdClass.</p>
<h3 id="heading-multiple-inheritances-interfaces-in-c">Multiple Inheritances – Interfaces in C</h3>
<p>Multiple inheritances are not supported in C#. But you can achieve it by using <em>interfaces</em>. </p>
<p>Multiple inheritances allow a derived class to be inherited from multiple parent classes. You can see an example of how a child class can inherit from multiple interfaces that act like a parent class below:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{    
    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-keyword">interface</span> <span class="hljs-title">InterfaceA</span>
        {
            <span class="hljs-comment">//...</span>
        }

        <span class="hljs-keyword">interface</span> <span class="hljs-title">InterfaceB</span>
        {
            <span class="hljs-comment">//...</span>
        }     

        <span class="hljs-keyword">class</span> <span class="hljs-title">NewClass</span>: <span class="hljs-title">InterfaceA</span>, <span class="hljs-title">InterfaceB</span>
        {
            <span class="hljs-comment">//...            </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">//...</span>
        }
    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Inheritance is important because it helps keep your code clean. It makes it easier to build families of related classes. The child class can inherit all the fields, properties, and methods that are contained in the parent class except those classes that are declared as a private class. </p>
<p>Through this article, I hope you have gained some insight about inheritance in C#.</p>
<p>Happy Coding.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Prototypes and Inheritance – and Why They Say Everything in JS is an Object ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this short article we're going to talk about prototypal inheritance in JavaScript, and what are the implications of it. Table of Contents Intro How to access a prototype’s properties and methods in JavaScript The prototype chain A... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/prototypes-and-inheritance-in-javascript/</link>
                <guid isPermaLink="false">66d45f1b3dce891ac3a967fe</guid>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Tue, 03 May 2022 16:05:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/pexels-maor-attias-5192478.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this short article we're going to talk about <strong>prototypal inheritance</strong> in JavaScript, and what are the implications of it.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-intro">Intro</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-access-a-prototypes-properties-and-methods-in-javascript">How to access a prototype’s properties and methods in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-prototype-chain">The prototype chain</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-prototype-based-language">A prototype-based language</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-javascript-classes">Javascript classes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-roundup">Roundup</a></p>
</li>
</ul>
<h1 id="heading-intro">Intro</h1>
<p>Have you ever wondered how strings, arrays or objects “know” the methods each of them have? How does a string know it can <code>.toUpperCase()</code> or an array know that it can <code>.sort()</code>? We never defined these methods manually, right?</p>
<p>The answer is that these methods come built-in within each type of data structure thanks to something called <strong>prototype inheritance</strong>.</p>
<p>In JavaScript, an object can inherit properties of another object. The object from where the properties are inherited is called the prototype. In short, objects can inherit properties from other objects — the prototypes.</p>
<p>You’re probably wondering: why the need for inheritance in the first place? Well, inheritance solves the problem of data and logic duplication. By inheriting, objects can share properties and methods without the need of manually setting those properties and methods on each object.</p>
<h2 id="heading-how-to-access-a-prototypes-properties-and-methods-in-javascript"><strong>How to</strong> A<strong>ccess</strong> a P<strong>rototype’s</strong> P<strong>roperties and</strong> M<strong>ethods</strong> in JavaScript</h2>
<p>When we try to access a property of an object, the property is not only searched in the object itself. It's also searched in the prototype of the object, in the prototype of the prototype, and so on – until a property is found that matches the name or the end of the <strong>prototype chain</strong> is reached.</p>
<p>If the property or method isn’t found anywhere in the prototype chain, only then will JavaScript return <code>undefined</code>.</p>
<p>Every object in JavaScript has an internal property called <code>[[Prototype]]</code>.</p>
<p>If we create an array and log it to the console like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(arr)
</code></pre>
<p>We will see this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The double square brackets that enclose <code>[[Prototype]]</code> signify that it is an internal property, and cannot be accessed directly in code.</p>
<p>To find the <code>[[Prototype]]</code> of an object, we will use the <code>Object.getPrototypeOf()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(arr))
</code></pre>
<p>The output will consist of several built-in properties and methods:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Keep in mind that prototypes can also be changed and modified through different methods.</p>
<h2 id="heading-the-prototype-chain"><strong>The</strong> P<strong>rototype</strong> C<strong>hain</strong></h2>
<p>At the end of the prototype chain is <code>Object.prototype</code>. All objects inherit the properties and methods of <code>Object</code>. Any attempt to search beyond the end of the chain results in <code>null</code>.</p>
<p>If you look for the prototype of the prototype of an array, a function, or a string, you’ll see it’s an object. And that’s because in JavaScript all objects are descendants or instances of <code>Object.prototype</code>, which is an object that sets properties and methods to all other JavaScript data types.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-keyword">const</span> arrProto = <span class="hljs-built_in">Object</span>.getPrototypeOf(arr)
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(arrProto))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Each type of prototype (for example array prototype) defines its own methods and properties, and in some cases overrides the <code>Object.prototype</code> methods and properties (that’s why arrays have methods that objects don’t).</p>
<p>But under the hood and going up the ladder of the prototype chain, <strong>everything in JavaScript is built upon the</strong> <code>Object.prototype</code>.</p>
<p>If we try to look into the prototype of <code>Object.prototype</code> we get <code>null</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-keyword">const</span> arrProto = <span class="hljs-built_in">Object</span>.getPrototypeOf(arr)
<span class="hljs-keyword">const</span> objectProto = <span class="hljs-built_in">Object</span>.getPrototypeOf(arrProto)
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(objectProto))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/image-3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-a-prototype-based-language"><strong>A Prototype-Based Language</strong></h2>
<p>JavaScript is a <strong>prototype-based language</strong>, meaning object properties and methods can be shared through generalized objects that have the ability to be cloned and extended.</p>
<p>When it comes to inheritance, JavaScript has only one structure: objects.</p>
<p>Each object has a private property (referred to as its <code>[[Prototype]]</code>) that maintains a link to another object called its prototype. That prototype object has its own prototype, and so on until an object whose prototype is <code>null</code> is reached.</p>
<p>By definition, <code>null</code> has no prototype, and acts as the final link in this chain of prototypes.</p>
<p>This is known as prototypical inheritance and differs from class inheritance. Among popular object-oriented programming languages, JavaScript is relatively unique, as other prominent languages such as PHP, Python, and Java are class-based languages, which instead define classes as blueprints for objects.</p>
<p>At this point you may be thinking "But we CAN implement classes on JavaScript!". And yes, we can, but as syntactic sugar. 🤫🤔</p>
<h2 id="heading-javascript-classes">Javascript Classes</h2>
<p>Classes are a way to set a blueprint to create objects with predefined properties and methods. By creating a class with specific properties and methods, you can later on instantiate objects from that class, that will inherit all the properties and methods that that class has.</p>
<p>In JavaScript, we can create classes in the following way:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Alien</span> </span>{
    <span class="hljs-keyword">constructor</span> (name, phrase) {
        <span class="hljs-built_in">this</span>.name = name
        <span class="hljs-built_in">this</span>.phrase = phrase
        <span class="hljs-built_in">this</span>.species = <span class="hljs-string">"alien"</span>
    }
    fly = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Zzzzzziiiiiinnnnnggggg!!"</span>)
    sayPhrase = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.phrase)
}
</code></pre>
<p>And then we can instantiate an object from that class like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> alien1 = <span class="hljs-keyword">new</span> Alien(<span class="hljs-string">"Ali"</span>, <span class="hljs-string">"I'm Ali the alien!"</span>)
<span class="hljs-built_in">console</span>.log(alien1.name) <span class="hljs-comment">// output: "Ali"</span>
</code></pre>
<p>Classes are used as a way to make code more modular, organized, and understandable and are heavily used in OOP programming.</p>
<p>But keep in mind that JavaScript doesn’t really support classes like other languages. The <code>class</code> keyword was introduced with ES6 as syntactic sugar that facilitates this way of organizing code.</p>
<p>To visualize this, see that the same thing we did by previously defining a <code>class</code>, we can do it by defining a function and editing the prototype in the following way:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Alien</span>(<span class="hljs-params">name, phrase</span>) </span>{
    <span class="hljs-built_in">this</span>.name = name
    <span class="hljs-built_in">this</span>.phrase = phrase
    <span class="hljs-built_in">this</span>.species = <span class="hljs-string">"alien"</span>
}

Alien.prototype.fly = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Zzzzzziiiiiinnnnnggggg!!"</span>)
Alien.prototype.sayPhrase = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.phrase)

<span class="hljs-keyword">const</span> alien1 = <span class="hljs-keyword">new</span> Alien(<span class="hljs-string">"Ali"</span>, <span class="hljs-string">"I'm Ali the alien!"</span>)

<span class="hljs-built_in">console</span>.log(alien1.name) <span class="hljs-comment">// output "Ali"</span>
<span class="hljs-built_in">console</span>.log(alien1.phrase) <span class="hljs-comment">// output "I'm Ali the alien!"</span>
alien1.fly() <span class="hljs-comment">// output "Zzzzzziiiiiinnnnnggggg"</span>
</code></pre>
<p>Any function can be invoked as a constructor with the keyword <code>new</code> and the prototype property of that function is used for the object to inherit methods from. In JavaScript, “class” is only used conceptually to describe the above practice – technically they’re just functions.😑</p>
<p>Although this doesn't necessarily make a lot of difference (we can still perfectly implement OOP and use classes like in most other programming languages), it's important to remember that JavaScript is built with prototype inheritance at its core.</p>
<h1 id="heading-roundup">Roundup</h1>
<p>That's it, everyone! As always, I hope you enjoyed the article and learned something new. If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>.</p>
<p>Cheers and see you in the next one! =D</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/AntiqueAthleticGuineapig-size_restricted.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Solve the Problem of Multiple Inheritance in Java ]]>
                </title>
                <description>
                    <![CDATA[ By Nahla Davies Java is one of the most popular object-oriented programming languages in use today.  Because it is platform-independent, you will find Java applications on every type of device and every operating system. And because Java is relativel... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-solve-multiple-inheritance-in-java/</link>
                <guid isPermaLink="false">66d46047264384a65d5a95a8</guid>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 01 Oct 2021 14:42:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/pexels-edward-jenner-4253062.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Nahla Davies</p>
<p>Java is one of the most popular object-oriented programming languages in use today. </p>
<p>Because it is platform-independent, you will find Java applications on every type of device and every operating system. And because <a target="_blank" href="https://www.freecodecamp.org/news/get-started-coding-with-java/">Java is relatively easy to learn</a>, it is one of the first languages that many programmers pick up.</p>
<p>An important feature of Java that you should be familiar with is class inheritance. Inheritance allows programmers to optimize code by facilitating class reuse. When you can reuse code that has already been tested and debugged, the software development life cycle becomes shorter and less costly.</p>
<p>While theoretically a simple concept, coding inheritance relationships require attention to detail. This is particularly true with respect to multiple inheritance, where a single child class inherits properties from multiple parent classes. </p>
<p>Java rejects multiple inheritance relationships because they create ambiguities, but there are a few ways you can accomplish many of the same effects if you know what to do.</p>
<p>In this article, we'll consider the problems with multiple inheritance and discuss alternative coding options in Java.</p>
<h2 id="heading-inheritance-terminology">Inheritance Terminology</h2>
<p>Sometimes, to be a successful programmer, you have to learn to problem solve in order to find workarounds for common bugs or problems. This is a necessary part of coding securely and smartly. </p>
<p>One such problem deals with multiple inheritance (or rather, the lack thereof) in Java.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/image-73.png" alt="Image" width="600" height="400" loading="lazy">
_<a target="_blank" href="https://www.tutorialspoint.com/java/java_inheritance.htm">Image Source</a>_</p>
<p>To fully understand inheritance in Java, you need to familiarize yourself with basic <a target="_blank" href="https://www.freecodecamp.org/news/java-object-oriented-programming-system-principles-oops-concepts-for-beginners/">object-oriented programming</a> (OOP) inheritance terminology. </p>
<ul>
<li><strong>Class:</strong> Classes are a fundamental template structure in object-oriented programming languages. A class defines the common properties for a group of objects.</li>
<li><strong>Parent Class:</strong> Also known as base classes or superclasses, a parent class is an extensible class that provides features to a child class. This is where reusability comes into play. The parent class definitions and functions are reused when creating child classes.</li>
<li><strong>Child Class:</strong> More generically called a subclass, a child class inherits features from another class. Child classes are extended or derived classes.</li>
<li><strong>Inheritance:</strong> The relationship between the parent and child classes.</li>
</ul>
<h2 id="heading-oop-inheritance-types">OOP Inheritance Types</h2>
<p>There are many popular object-oriented programming languages in use today, including <a target="_blank" href="https://stackoverflow.blog/2021/02/22/choosing-java-instead-of-c-for-low-latency-systems/">Java, C++</a>, JavaScript, Python, PHP, Ruby, and Perl. While inheritance is a common concept across these OOP languages, not all inheritance types exist in each language.</p>
<p>It is crucial to know the general inheritance types and the limitations on inheritance in the specific language you are using. The more you know about inheritance, the more effective a software developer you will be. </p>
<p>Types of inheritance supported by Java include:</p>
<ul>
<li><strong>Single-level inheritance:</strong> When a child class derives features from a single parent class.</li>
<li><strong>Multi-level inheritance:</strong> This is a tiered form of single-level inheritance. In multi-level inheritance, a child class can also act as a parent class to other child classes. The relationship between each level is linear – no branches are extending above as in multiple inheritance. The ultimate child class then has features from every level above it.</li>
<li><strong>Hierarchical inheritance:</strong> The opposite of multiple inheritance. In hierarchical inheritance, a single parent class has more than one child class. So rather than having branches above it, it branches below.</li>
<li><strong>Hybrid inheritance:</strong> As its name suggests, hybrid inheritance is a combination of other inheritance types.</li>
</ul>
<p>In addition to the inheritance types above, there are other types that Java does not support.</p>
<ul>
<li><strong>Multiple inheritance:</strong> In multiple inheritance, a child class has more than one parent class. While Java and <a target="_blank" href="https://www.freecodecamp.org/news/functional-programming-in-javascript-for-beginners/">JavaScript</a> do not support multiple inheritance, OOP languages such as C++ do.</li>
<li><strong>Multipath inheritance:</strong> A hybrid of multiple, multi-level, and hierarchical inheritance, in multipath inheritance a child class derives its features and functions from a parent class and several child classes of the parent class. Because multipath inheritance relies on multiple inheritance, Java does not support its use.</li>
</ul>
<h2 id="heading-why-java-doesnt-support-multiple-inheritance">Why Java Doesn’t Support Multiple Inheritance</h2>
<p>The primary problem with multiple inheritance is that it has the potential to create ambiguities in child classes. In a 1995 overview whitepaper, Java lead designer James Gosling stated that the <a target="_blank" href="https://www.researchgate.net/publication/345758345_Java_an_Overview_the_original_Java_whitepaper">issues with multiple inheritance</a> were one of the motivations for the creation of Java.</p>
<p>The difficulties inherent in multiple inheritance are most clearly seen in the diamond problem. In <a target="_blank" href="https://www.freecodecamp.org/news/multiple-inheritance-in-c-and-the-diamond-problem-7c12a9ddbbec/">the diamond problem</a>, parent class A has two distinct child classes B and C; that is, child classes B and C extend class A.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/image-74.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://www.dotnettricks.com/learn/oops/understanding-inheritance-and-different-types-of-inheritance">Image Source</a></em></p>
<p>Now we create a new child class D, which extends both class B and class C. Note that we have multiple inheritance (D extends B and C), hierarchical inheritance (B and C extend A), and multilevel inheritance (D extends A, B, and C).</p>
<p>In the diamond problem, child classes B and C inherit a method from parent class A. Both B and C override the inherited method. But the new methods in B and C conflict with each other. </p>
<p>Ultimate child class D inherits the two independent and conflicting methods from its multiple parents B and C. It is unclear which method class D should use, so there is ambiguity. Other OOP programming languages implement various methods for addressing the multiple inheritance ambiguity.</p>
<h2 id="heading-how-to-solve-the-multiple-inheritance-problem-in-java">How to Solve the Multiple Inheritance Problem in Java</h2>
<p>Just because multiple inheritance is problematic does not mean that it is not useful. There are many situations where you may want one class to have features from several other classes. </p>
<p>Just think about that Tesla Roadster you will buy when you become a wildly successful software developer. It will draw characteristics from both the sports car class and the electric car class. </p>
<p>Or maybe you are using a private browser to read this article, which has features from the online data privacy solution class and the general internet browser class.</p>
<p>But you can’t extend multiple classes in Java. So how does Java deal with the multiple inheritance issue? </p>
<p>Well, it uses structures called interfaces. Interfaces are <a target="_blank" href="https://www.freecodecamp.org/news/java-interfaces-explained-with-examples/">abstract types that specify behaviors</a> for classes to implement. Because they are abstract, interfaces do not contain detailed instructions for their behaviors. Instead, the classes provide concrete implementations of interface behaviors.</p>
<p>Interfaces have several defining characteristics:</p>
<ul>
<li>Unlike classes, you do not instantiate interfaces. Instead, classes implement interfaces</li>
<li>Interfaces contain only public constant definitions and method headers</li>
<li>Interfaces can only extend other interfaces, not classes</li>
<li>Interfaces can extend multiple interfaces, and classes can implement multiple interfaces</li>
</ul>
<p>Now, we can effectively bypass the diamond problem with interfaces. Recalling that only interfaces can only extend other interfaces and any class that needs multiple inheritance characteristics must implement multiple interfaces, we can redefine the diamond problem classes. </p>
<p>What were previously classes A, B, and C now become interfaces A, B, and C. Interfaces B and C still extend interface A, but there are no concrete functions in any of these interfaces, just defined behaviors. Class D remains a class, which is responsible for the concrete implementation of the behaviors found in interfaces B and C. </p>
<p>Note one key distinction here: Class D is not extending interfaces B and C. It is instead implementing them. So you do not actually have a multiple inheritance. Instead, you have simply redefined the problem.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding inheritance is necessary for any effective coder. For Java programmers, it is equally important to know the limitations of inheritance and the built-in Java workaround for the traditional problems with multiple inheritance. </p>
<p>Learning <a target="_blank" href="https://www.freecodecamp.org/news/polymorphism-in-java-tutorial-with-object-oriented-programming-example-code/">how to put interfaces in place</a> to recreate the effects of multiple inheritance in Java will increase your effectiveness and hireability.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Inheritance in Java Explained ]]>
                </title>
                <description>
                    <![CDATA[ Inheritance Java inheritance refers to the ability of a Java Class to inherit the properties from some other Class. Think of it like a child inheriting properties from its parents, the concept is very similar to that. In Java lingo, it is also called... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/inheritance-in-java-explained/</link>
                <guid isPermaLink="false">66c3580271e87702d4e5b6da</guid>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 18 Jan 2020 19:08:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9dc4740569d1a4ca3982.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h1 id="heading-inheritance"><strong>Inheritance</strong></h1>
<p>Java inheritance refers to the ability of a Java Class to <code>inherit</code> the properties from some other Class. Think of it like a child inheriting properties from its parents, the concept is very similar to that. In Java lingo, it is also called <em>extend</em>-ing a class. </p>
<p>Some simple things to remember:</p>
<ul>
<li>The Class that extends or inherits is called a <strong>subclass</strong></li>
<li>The Class that is being extended or inherited is called a <strong>superclass</strong></li>
</ul>
<p>Thus, inheritance gives Java the cool capability of <em>re-using</em> code, or sharing code between classes!</p>
<p>Let’s describe it with the classic example of a <code>Vehicle</code> class and a <code>Car</code> class :</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// starting the engine</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">stop</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// stopping the engine</span>
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-keyword">int</span> numberOfSeats = <span class="hljs-number">4</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getNumberOfSeats</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> numberOfSeats;
    }
}
</code></pre>
<p>Here, we can see the <code>Car</code> class inheriting the properties of the <code>Vehicle</code> class. So, we don’t have to write the same code for the methods <code>start()</code> and <code>stop()</code> for <code>Car</code> as well, as those properties are available from its parent or superclass. Therefore, objects created from the <code>Car</code> class will <em>also</em> have those properties!</p>
<pre><code class="lang-java">Car tesla = <span class="hljs-keyword">new</span> Car();

tesla.start();

tesla.stop();
</code></pre>
<p><a target="_blank" href="https://repl.it/CJXz/0">Run Code</a></p>
<p>But, does the parent class have the methods of the child? No, it doesn’t.</p>
<p>Therefore, whenever you need to share some common piece of code between multiple classes, it is always good to have a parent class, and then extend that class whenever needed! Reduces the number of lines of code, makes code modular, and simplifies testing.</p>
<h2 id="heading-what-can-be-inherited"><strong>What can be inherited ?</strong></h2>
<ul>
<li>All <code>protected</code> and <code>public</code> fields and methods from parent</li>
</ul>
<h2 id="heading-what-cannot-be-inherited"><strong>What cannot be inherited ?</strong></h2>
<ul>
<li><code>private</code> fields and methods</li>
<li>Constructors. Although, the subclass constructor <em>has</em> to call the superclass constructor if its defined (More on that later!)</li>
<li>Multiple classes. Java supports only <strong>single inheritance</strong>, that is, you can only inherit one class at a time.</li>
<li>Fields. Individual fields of a class cannot be overriden by the subclass.</li>
</ul>
<h2 id="heading-type-casting-amp-reference"><strong>Type Casting &amp; Reference</strong></h2>
<p>In Java, it is possible to reference a subclass as an <em>instance</em> of its superclass. It is called <em>Polymorphism</em> in Object Oriented Programming (OOP), the ability for an object to take on many forms. For example, the <code>Car</code> class object can be referenced as a <code>Vehicle</code> class instance like this :</p>
<pre><code class="lang-java">Vehicle car = <span class="hljs-keyword">new</span> Car();
</code></pre>
<p>Although, the opposite is not possible :</p>
<pre><code class="lang-java">Car car = <span class="hljs-keyword">new</span> Vehicle(); <span class="hljs-comment">// ERROR</span>
</code></pre>
<p><a target="_blank" href="https://repl.it/CJYB/0">Run Code</a></p>
<p>Since you can reference a Java subclass as a superclass instance, you can easily cast an instance of a subclass object to a superclass instance. It is possible to cast a superclass object into a subclass type, but <em>only if the object is really an instance of the subclass</em>. So keep this in mind :</p>
<pre><code class="lang-java">Car car = <span class="hljs-keyword">new</span> Car();
Vehicle vehicle = car; <span class="hljs-comment">// upcasting</span>
Car car2 = (Car)vechile; <span class="hljs-comment">//downcasting</span>

Bike bike = <span class="hljs-keyword">new</span> Bike(); <span class="hljs-comment">// say Bike is also a subclass of Vehicle</span>
Vehicle v = bike; <span class="hljs-comment">// upcasting, no problem here.</span>
Car car3 = (Car)bike; <span class="hljs-comment">// Compilation Error : as bike is NOT a instance of Car</span>
</code></pre>
<p><a target="_blank" href="https://repl.it/CJYM/0">Run Code</a></p>
<p>Now you know how to share code through a parent-child relationship. But, what if, you do not like the implementation of a particular method in the child class and want to write a new one for it? What do you do then?</p>
<h2 id="heading-override-it"><strong>Override it!</strong></h2>
<p>Java lets you <em>override</em> or redefine the methods defined in the superclass. For example, your <code>Car</code> class has a different implementation of <code>start()</code> than the parent <code>Vehicle</code>, so you do this :</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span> </span>{
      System.out.println(<span class="hljs-string">"Vehicle start code"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span> </span>{
      System.out.println(<span class="hljs-string">"Car start code"</span>);
  }
}

Car car = <span class="hljs-keyword">new</span> Car();
car.start(); <span class="hljs-comment">// "Car start code"</span>
</code></pre>
<p><a target="_blank" href="https://repl.it/CJYZ/1">Run Code</a></p>
<p>So, it’s pretty simple to override methods in the subclass. Although, there is a <em>catch</em>. Only that superclass method with the <em>exact same method signature</em> as the subclass method will be overriden. That means the subclass method definition must have the exact same name, same number and type of parameters, and in the exact same sequence. Thus, <code>public void start(String key)</code> would not override <code>public void start()</code>.</p>
<p><strong>Notes</strong> :</p>
<ul>
<li>You cannot override private methods of the superclass. (Quite obvious, isn’t it?)</li>
<li>What if the method of superclass which you are overriding in the subclass suddenly gets obliterated or methods changed? It would fail in runtime! So Java provides you a nifty annotation <code>@Override</code> which you can place over the subclass method, which will warn the compiler of those incidents!</li>
</ul>
<p>Annotations in Java is a good coding practice, but they are not a necessity. The compiler is smart enough to figure out overriding on its own though. Unlike other OOP languages, Annotations in Java it doesn’t necessarily modify the method or add extra functionality.</p>
<h2 id="heading-how-to-call-super-class-methods"><strong>How to call super class methods?</strong></h2>
<p>Funny you ask about it! Just use the keyword <code>super</code> :</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> class <span class="hljs-title">Vehicle</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span> </span>{
      System.out.println(<span class="hljs-string">"Vehicle start code"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
      <span class="hljs-keyword">super</span>.start();
  }
}

Car car = <span class="hljs-keyword">new</span> Car();
car.run(); <span class="hljs-comment">// "Vehicle start code"</span>
</code></pre>
<p><a target="_blank" href="https://repl.it/CJY4/0">Run Code</a></p>
<p><strong>N.B.</strong> : Although you can call the parent method by using a <code>super</code> call, you cannot go up the inheritance hierarchy with chained <code>super</code> calls.</p>
<h2 id="heading-how-to-know-the-type-of-a-class"><strong>How to know the type of a class?</strong></h2>
<p>Using the <code>instanceof</code> keyword. Having lots of classes and subclasses it would be a little confusing to know which class is a subclass of which one in runtime. So, we can use <code>instanceof</code> to determine whether an object is an instance of a class, an instance of a subclass, or an instance of an interface.</p>
<pre><code class="lang-java">Car car = <span class="hljs-keyword">new</span> Car();

<span class="hljs-keyword">boolean</span> flag = car <span class="hljs-keyword">instanceof</span> Vehicle; <span class="hljs-comment">// true in this case!</span>
</code></pre>
<h2 id="heading-constructors-amp-inheritance"><strong>Constructors &amp; Inheritance</strong></h2>
<p>As mentioned earlier, constructors cannot be directly inherited by a subclass. Although, a subclass is <em>required</em> to call its parent’s constructor as the <a target="_blank" href="http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor">first operation</a> in its own constructor. How? You guessed it, using <code>super</code> :</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Vehicle</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// constructor</span>
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span> </span>{
      System.out.println(<span class="hljs-string">"Vehicle start code"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Car</span><span class="hljs-params">()</span> </span>{
      <span class="hljs-keyword">super</span>();
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
      <span class="hljs-keyword">super</span>.start();
  }
}
</code></pre>
<p><a target="_blank" href="https://repl.it/CJY8/0">Run Code</a></p>
<p>Remember, if the superclass does not have any constructors defined, you don’t have to call it explicitely in the subclass. Java handles that internally for you! Invocation to <code>super</code> constructor is done in the case when the super class is to be called with any other constructor other than the <em>default constructor</em>.</p>
<p>If no other constructors are defined, then Java invokes the default super class constructor (<em>even if not defined explicitly</em>).</p>
<p>Congrats, now you know all about Inheritance! Read more about advanced ways to inherit things in Abstract Classes and <a target="_blank" href="https://forum.freecodecamp.com/t/java-docs-interfaces">Interfaces</a>!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
