<?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" version="2.0"><channel><title><![CDATA[J B Sankarlal's Blog]]></title><description><![CDATA[J B Sankarlal's Blog]]></description><link>https://blog.sankarlal.in</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1696623274000/jom-9-Zbn.png</url><title>J B Sankarlal&apos;s Blog</title><link>https://blog.sankarlal.in</link></image><generator>RSS for Node</generator><lastBuildDate>Thu, 21 May 2026 17:29:17 GMT</lastBuildDate><atom:link href="https://blog.sankarlal.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Mojo: The Programming Language That Could Redefine AI Development]]></title><description><![CDATA[Artificial Intelligence (AI) is growing at lightning speed and so are the tools used to build it. If you’ve ever found Python too slow for big machine learning tasks, or felt overwhelmed by the complexity of faster languages like C++, you’re not alon...]]></description><link>https://blog.sankarlal.in/mojo-the-programming-language-that-could-redefine-ai-development</link><guid isPermaLink="true">https://blog.sankarlal.in/mojo-the-programming-language-that-could-redefine-ai-development</guid><category><![CDATA[Python]]></category><category><![CDATA[MOJO]]></category><category><![CDATA[Mojo vs Python]]></category><category><![CDATA[AI]]></category><category><![CDATA[AI development]]></category><dc:creator><![CDATA[J B Sankarlal]]></dc:creator><pubDate>Fri, 02 May 2025 19:54:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746217407310/c2787005-d7f0-4f65-8a81-c4cad0f7f1e4.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Artificial Intelligence (AI) is growing at lightning speed and so are the tools used to build it. If you’ve ever found Python too slow for big machine learning tasks, or felt overwhelmed by the complexity of faster languages like C++, you’re not alone. That’s where <strong>Mojo</strong> comes in as a new programming language that combines Python’s ease of use with the speed and power of low-level languages.</p>
<p>In this blog, I’ll explain what Mojo is, why it’s important, and how it could shape the future of AI development.</p>
<h2 id="heading-so-what-is-mojo">So, What is Mojo?</h2>
<p>Mojo is a programming language created by Modular, made especially for AI developers. It’s designed to be as easy to use as Python, but with the speed of C++. Mojo isn’t just another language, it’s built to work efficiently with modern AI hardware like GPUs (For those who don’t know: <strong>Graphics Processing Unit</strong> is a specialized processor designed to handle the complex calculations needed to render images and videos on a screen) and TPUs.</p>
<p>Here’s the best part: Mojo is compatible with Python, so you can use what you already know, while also gaining powerful features like better memory control, stronger typing, and multithreading when needed.</p>
<h2 id="heading-why-mojo-stands-out">Why Mojo Stands Out ?</h2>
<h3 id="heading-pythonic-syntax">Pythonic Syntax</h3>
<p>Mojo code looks and feels like Python. If you're comfortable writing Python, the learning curve for Mojo is surprisingly gentle.</p>
<h3 id="heading-unmatched-performance">Unmatched Performance</h3>
<p>Mojo compiles down to machine code and leverages features like static typing (If u don’t know : datatype is defined when you write the code), zero-cost abstractions (a feature that allow us to write clean code without comprimising the performance) , and fine-grained hardware control. This makes it an ideal choice for developers looking to enhance their AI applications without sacrificing ease of use.</p>
<h3 id="heading-system-programming-ai">System Programming + AI</h3>
<p>In the past, system programming and AI development were separate areas. Mojo connects these two, allowing you to write both low-level kernels and high-level model logic using one language.</p>
<h3 id="heading-full-hardware-control">Full Hardware Control</h3>
<p>You will get direct access to GPUs, vector units, and custom AI chips, something Python doesn’t offer natively.</p>
<h2 id="heading-have-a-look-at-this-sample-code">Have a look at this sample code</h2>
<pre><code class="lang-python">fn square(x: Int) -&gt; Int:
    <span class="hljs-keyword">return</span> x * x

print(square(<span class="hljs-number">5</span>))  <span class="hljs-comment"># Output: 25</span>

<span class="hljs-comment">#NB: this isn't Python</span>
</code></pre>
<ul>
<li><p><code>fn</code> indicates that you're defining a <strong>function</strong>.</p>
</li>
<li><p><code>square</code> is the <strong>name</strong> of the function.</p>
</li>
<li><p><code>(x: Int)</code> is the <strong>parameter</strong>. <code>x</code> is the input to the function, and <code>Int</code> specifies that <code>x</code> is expected to be an <strong>integer</strong> (a whole number).</p>
</li>
<li><p><code>-&gt; Int</code> means the function will return an <strong>integer</strong> (specifically, the result of squaring <code>x</code>).</p>
</li>
</ul>
<p>The function <code>square</code> takes an integer, multiplies it by itself, and returns the result. When you call <code>square(5)</code>, it outputs <code>25</code> because 5 squared equals 25.</p>
<h2 id="heading-where-mojo-fits-in">Where Mojo Fits In</h2>
<ul>
<li><p>Creating fast machine learning kernels</p>
</li>
<li><p>Improving model performance on edge devices(local computing devices)</p>
</li>
<li><p>Running AI on special chips</p>
</li>
<li><p>Replacing important performance parts of Python-based machine learning pipelines</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Mojo may still be in its early days, but its potential is undeniable. With seamless Python compatibility, powerful hardware access, and lightning-fast performance, it’s primed to become the go-to language for AI development in the near future. The combination of simplicity and speed could truly reshape how we build and scale AI applications.The future of AI development is looking brighter than ever!</p>
<p>Thanks for reading, and stay tuned for more updates!</p>
]]></content:encoded></item><item><title><![CDATA[Step-by-Step Guide for Access and Refresh Tokens]]></title><description><![CDATA[Whenever we set up authentication and authorization using JWT (JSON Web Tokens), it's important to ensure the use of refresh tokens to enhance security and provide continuous access without requiring the user to log in frequently.
Authentication vs A...]]></description><link>https://blog.sankarlal.in/step-by-step-guide-for-access-and-refresh-tokens</link><guid isPermaLink="true">https://blog.sankarlal.in/step-by-step-guide-for-access-and-refresh-tokens</guid><category><![CDATA[JWT]]></category><category><![CDATA[refresh-token]]></category><category><![CDATA[refreshtoken]]></category><category><![CDATA[access-token]]></category><category><![CDATA[JSON Web Tokens (JWT)]]></category><dc:creator><![CDATA[J B Sankarlal]]></dc:creator><pubDate>Tue, 24 Sep 2024 19:41:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727206707124/bd4cbb1d-b856-4605-afb5-466bac655ca2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Whenever we set up <strong>authentication and authorization</strong> using <strong>JWT (JSON Web Tokens)</strong>, it's important to ensure the use of <strong>refresh tokens</strong> to enhance security and provide continuous access without requiring the user to log in frequently.</p>
<h3 id="heading-authentication-vs-authorization">Authentication vs Authorization</h3>
<p><strong>Authentication</strong> is about confirming ‘<strong>who you are’</strong>. It's the process of verifying your identity, like when you log in to a website with a username and password. The system checks if you are who you say you are.</p>
<p><strong>Authorization</strong> is about checking ‘<strong>what you are allowed to do’</strong>. After you're authenticated, the system checks if you have permission to access certain resources or perform specific actions, like viewing a page or editing a file.</p>
<h3 id="heading-jwt">JWT</h3>
<p><strong>JWT (JSON Web Token)</strong> is like a digital ID card. When you log in to a website or app, the server gives you this "ID card" (the JWT), which proves who you are.</p>
<ul>
<li><p>It's a small piece of information, made up of three parts: <strong>header</strong>, <strong>payload</strong>, and <strong>signature</strong>.</p>
</li>
<li><p>You send this token every time you make a request (like visiting a new page or getting data) to prove you're logged in.</p>
</li>
<li><p>The server doesn't need to look you up in a database every time—it just checks the token.</p>
</li>
</ul>
<p>Think of JWT as a fast and secure way for the server to remember who you are and what you're allowed to do.</p>
<p><img src="https://fusionauth.io/img/shared/json-web-token.png" alt /></p>
<h3 id="heading-parts-of-jwt">Parts of JWT</h3>
<p>A JWT consists of three parts separated by periods ‘.’, which are base64url-encoded strings:</p>
<ol>
<li><p><strong>Header</strong>: The header typically consists of two parts;</p>
<p> a. the token type (JWT)</p>
<p> b. the signing algorithm being used, such as HMAC SHA256 or RSA.</p>
<p> Example</p>
<pre><code class="lang-javascript"> {
  <span class="hljs-string">"alg"</span>: <span class="hljs-string">"HS256"</span>,
  <span class="hljs-string">"typ"</span>: <span class="hljs-string">"JWT"</span>
 }
</code></pre>
</li>
<li><p><strong>Payload</strong>: The payload contains the claims, which are statements about the user or other data. Claims can be of three types: registered, public, and private claims.</p>
<p> Example:</p>
<pre><code class="lang-javascript"> {
   <span class="hljs-string">"sub"</span>: <span class="hljs-string">"user1"</span>,
   <span class="hljs-string">"name"</span>: <span class="hljs-string">"Sankarlal"</span>,
   <span class="hljs-string">"admin"</span>: <span class="hljs-literal">true</span>
 }
</code></pre>
<p> <strong>Signature</strong>: To create the signature part, you need to take the encoded header, encoded payload, a secret, and the algorithm specified in the header, then sign that with the secret. The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed along the way.</p>
<p> Example (using HMAC SHA256):</p>
</li>
<li><pre><code class="lang-javascript">  HMACSHA256(
    base64UrlEncode(header) + <span class="hljs-string">"."</span> + base64UrlEncode(payload),
    secret
  )
</code></pre>
</li>
</ol>
<h3 id="heading-working-of-jwt">Working of JWT</h3>
<p><img src="https://miro.medium.com/v2/resize:fit:828/format:webp/1*TNF50fkV0LDWtgZO8MsNOQ.jpeg" alt /></p>
<p>When a user logs in or attempts to access a protected resource, the server generates a JWT after successful authentication(login process).</p>
<p>The client then stores this token, usually in local storage or a cookie.</p>
<p>For every subsequent request that requires authentication, the client sends the JWT in the request headers.</p>
<p>The server checks the token to make sure it’s valid and that the user has the right permissions before allowing access.</p>
<h3 id="heading-access-tokens">ACCESS TOKENS</h3>
<p>Access tokens are temporary keys that allow users to access specific resources after logging in. They contain user information and are sent with requests to verify permissions, usually expiring after a short time for added security.</p>
<h3 id="heading-refresh-tokens">REFRESH TOKENS</h3>
<p>A refresh token is a special type of key that helps you get new access tokens. This way, you can use short-lived access tokens that expire quickly without needing to log in again each time one runs out.</p>
<p>Access tokens contain user information and are valid for a short time. Refresh tokens, on the other hand, are kept safe as HTTP-only cookies(a type of cookie that can only be accessed by the server and not by client-side scripts, such as JavaScript). They allow you to stay logged in longer without risking your sensitive information being accessed by client-side JavaScript.</p>
<h2 id="heading-integrating-access-and-refresh-tokens">Integrating Access and Refresh Tokens</h2>
<h4 id="heading-step-1-setup-environment">Step 1: Setup Environment</h4>
<ul>
<li><p><strong>Install Dependencies</strong>: Make sure you have the necessary packages installed: <code>dotenv</code>, <code>express</code>, <code>cookie-parser</code>, and <code>jsonwebtoken</code>.</p>
</li>
<li><p><strong>Environment Variables</strong>: Set up your <code>.env</code> file with two secrets:</p>
<pre><code class="lang-javascript">  ACCESS_TOKEN_SECRET=your_access_token_secret
  REFRESH_TOKEN_SECRET=your_refresh_token_secret
</code></pre>
</li>
</ul>
<h4 id="heading-step-2-initialize-express-app">Step 2: Initialize Express App</h4>
<ul>
<li><p><strong>Create an Express Application</strong>: Use Express to handle HTTP requests.</p>
</li>
<li><p><strong>Middleware Configuration</strong>: Set up middleware to parse JSON and URL-encoded data, and to handle cookies.</p>
</li>
<li><pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> app = express();
    app.use(express.json());
    app.use(express.urlencoded({ <span class="hljs-attr">extended</span>: <span class="hljs-literal">false</span> }));
    app.use(cookieparser());
</code></pre>
</li>
</ul>
<h4 id="heading-step-3-define-user-credentials">Step 3: Define User Credentials</h4>
<ul>
<li><p><strong>Simulated User Data</strong>: Create an object with sample user credentials for authentication.</p>
</li>
<li><pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> userCredentials = {
        <span class="hljs-attr">username</span>: <span class="hljs-string">'sankar'</span>,
        <span class="hljs-attr">password</span>: <span class="hljs-string">'sankarlal2024'</span>,
        <span class="hljs-attr">email</span>: <span class="hljs-string">'sankarlal@gmail.com'</span>
    }
</code></pre>
</li>
</ul>
<h4 id="heading-step-4-implement-login-route">Step 4: Implement Login Route</h4>
<ul>
<li><p><strong>Handle Login Requests</strong>: Create a POST endpoint <code>/login</code> to authenticate users.</p>
</li>
<li><p><strong>Check Credentials</strong>: Verify the provided username and password against the stored credentials.</p>
</li>
<li><pre><code class="lang-javascript">    app.post(<span class="hljs-string">'/login'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
       <span class="hljs-comment">// Destructuring username &amp;amp; password from body</span>
        <span class="hljs-keyword">const</span> { username, password } = req.body;

       <span class="hljs-comment">// Checking if credentials match</span>
        <span class="hljs-keyword">if</span> (username === userCredentials.username &amp;&amp;
            password === userCredentials.password) {

      <span class="hljs-comment">//creating a access token</span>
           <span class="hljs-keyword">const</span> accessToken = jwt.sign({
            <span class="hljs-attr">username</span>: userCredentials.username,
            <span class="hljs-attr">email</span>: userCredentials.email
             }, process.env.ACCESS_TOKEN_SECRET, { <span class="hljs-attr">expiresIn</span>: <span class="hljs-string">'10m'</span> });

     <span class="hljs-comment">// Creating refresh token not that expiry of refreh token</span>

            <span class="hljs-keyword">const</span> refreshToken = jwt.sign({
                <span class="hljs-attr">username</span>: userCredentials.username,
            }, process.env.REFRESH_TOKEN_SECRET, { <span class="hljs-attr">expiresIn</span>: <span class="hljs-string">'1d'</span> });

            <span class="hljs-comment">// Assigning refresh token in http-only cookie </span>
            res.cookie(<span class="hljs-string">'jwt'</span>, refreshToken, {
                <span class="hljs-attr">httpOnly</span>: <span class="hljs-literal">true</span>,
                <span class="hljs-attr">sameSite</span>: <span class="hljs-string">'None'</span>, 
                <span class="hljs-attr">secure</span>: <span class="hljs-literal">true</span>,
                <span class="hljs-attr">maxAge</span>: <span class="hljs-number">24</span> * <span class="hljs-number">60</span> * <span class="hljs-number">60</span> * <span class="hljs-number">1000</span>
            });
            <span class="hljs-keyword">return</span> res.json({ accessToken });
        }
        <span class="hljs-keyword">else</span> {
            <span class="hljs-comment">// Return unauthorized error if credentials don't match</span>
            <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">406</span>).json({
                <span class="hljs-attr">message</span>: <span class="hljs-string">'Invalid credentials'</span>
            });
        }
    })
</code></pre>
</li>
</ul>
<h4 id="heading-step-5-implement-token-refresh-route">Step 5: Implement Token Refresh Route</h4>
<ul>
<li><p><strong>Handle Refresh Requests</strong>: Create a POST endpoint <code>/refresh</code> to obtain a new access token using the refresh token.</p>
</li>
<li><p><strong>Verify Refresh Token</strong>: Check if the refresh token exists and is valid.</p>
</li>
<li><pre><code class="lang-javascript">    app.post(<span class="hljs-string">'/refresh'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span> (req.cookies?.jwt) {

     <span class="hljs-comment">// Destructuring refreshToken from cookie</span>
            <span class="hljs-keyword">const</span> refreshToken = req.cookies.jwt;

      <span class="hljs-comment">// Verifying refresh token</span>
            jwt.verify(refreshToken, process.env.REFRESH_TOKEN_SECRET,
                <span class="hljs-function">(<span class="hljs-params">err, decoded</span>) =&gt;</span> {
                    <span class="hljs-keyword">if</span> (err) {
                        <span class="hljs-comment">// Wrong Refesh Token</span>
                <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">406</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Unauthorized'</span> });
                    }
                    <span class="hljs-keyword">else</span> {
                        <span class="hljs-comment">// Correct token we send a new access token</span>
                        <span class="hljs-keyword">const</span> accessToken = jwt.sign({
                            <span class="hljs-attr">username</span>: userCredentials.username,
                            <span class="hljs-attr">email</span>: userCredentials.email
                        }, process.env.ACCESS_TOKEN_SECRET, {
                            <span class="hljs-attr">expiresIn</span>: <span class="hljs-string">'15m'</span>
                        });
                        <span class="hljs-keyword">return</span> res.json({ accessToken });
                    }
                })
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">406</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Unauthorized'</span> });
        }
    })
</code></pre>
</li>
</ul>
<h4 id="heading-step-6-start-the-server">Step 6: Start the Server</h4>
<ul>
<li><p><strong>Run the Application</strong>: Listen on a specified port to start the server.</p>
</li>
<li><pre><code class="lang-javascript">    app.listen(<span class="hljs-number">6700</span>, <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server active on http://localhost:<span class="hljs-subst">${<span class="hljs-number">6700</span>}</span>!`</span>);
    });
</code></pre>
</li>
</ul>
<p>So this code demonstrates how to use access tokens for immediate access and refresh tokens for prolonged authentication. The access token is short-lived and needs to be refreshed periodically using the refresh token stored securely in an HTTP-only cookie, ensuring better security and user experience.</p>
]]></content:encoded></item><item><title><![CDATA[ENCAPSULATION - Java OOPs Simplified Part 6]]></title><description><![CDATA[This is one of the four pillars of Object-Oriented Programming. So let's dive in detail to understand what it really is.
What is Encapsulation?
Just imagine a capsule pill. The medicine inside the capsule is not exposed directly. Instead, it's encaps...]]></description><link>https://blog.sankarlal.in/encapsulation-in-java</link><guid isPermaLink="true">https://blog.sankarlal.in/encapsulation-in-java</guid><category><![CDATA[encapsulation]]></category><category><![CDATA[OOPS]]></category><category><![CDATA[Java]]></category><category><![CDATA[getter and setter]]></category><dc:creator><![CDATA[J B Sankarlal]]></dc:creator><pubDate>Sun, 02 Jun 2024 10:12:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717326707589/788834b9-20eb-48da-8270-a0f9a4f705c1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is one of the four pillars of Object-Oriented Programming. So let's dive in detail to understand what it really is.</p>
<h3 id="heading-what-is-encapsulation">What is Encapsulation?</h3>
<p>Just imagine a capsule pill. The medicine inside the capsule is not exposed directly. Instead, it's encapsulated within a shell. You can only access the medicine by consuming the capsule. This ensures that the medicine is protected and delivered in the right way.</p>
<p>In the same way, in Java, encapsulation is like putting your data (variables) inside a protective shell (class) and controlling access to it through methods.</p>
<h3 id="heading-now-lets-look-at-an-example">Now let's look at an Example.</h3>
<p>Let's say we have a <code>Student</code>class. We want to keep the student's age private and control how it's accessed and modified.</p>
<ol>
<li><p><strong>Define the class with private fields</strong>:</p>
<ul>
<li>We make the <code>age</code> field private so it cannot be accessed directly from outside the class.</li>
</ul>
</li>
<li><p><strong>Provide public methods to access and modify the age</strong>:</p>
<ul>
<li>We create public <mark>getter and setter methods</mark> to access and update the age.</li>
</ul>
</li>
</ol>
<p>Let's look at the code illustration for 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">Student</span></span>{
    <span class="hljs-comment">// declare age as private field</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

    <span class="hljs-comment">// a public method to get the age</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> age;
    }

    <span class="hljs-comment">// now, a public method to set the age with some validation</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-keyword">if</span> (age &gt;= <span class="hljs-number">0</span>) { <span class="hljs-comment">// Validating that age cannot be negative</span>
            <span class="hljs-keyword">this</span>.age = age;
        } <span class="hljs-keyword">else</span> {
            System.out.println(<span class="hljs-string">"Age cannot be negative"</span>);
        }
    }
}
</code></pre>
<p>Now, let's look how can we use the "Student" 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">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Student s1= <span class="hljs-keyword">new</span> Student();

        <span class="hljs-comment">// Set the age using the setter method</span>
        s1.setAge(<span class="hljs-number">16</span>);

        <span class="hljs-comment">// Get the age using the getter method</span>
        System.out.println(<span class="hljs-string">"Student's age: "</span> + s1.getAge());

        <span class="hljs-comment">// Try to set an invalid age</span>
        s1.setAge(-<span class="hljs-number">5</span>); <span class="hljs-comment">// This will print "Age cannot be negative"</span>
    }
}
</code></pre>
<p>So, here we are implementing two things,</p>
<ol>
<li><strong>Setting the Age</strong>:</li>
</ol>
<ul>
<li><p><code>s1.setAge(16);</code></p>
</li>
<li><p>This line calls the <code>setAge</code>method on the <code>Student</code>object, passing "16" as an argument. The <code>setAge</code>method updates the private <code>age</code>field with this value.</p>
</li>
</ul>
<ol start="2">
<li><p><strong>Getting the Name</strong>:</p>
<ul>
<li><p><code>System.out.println("Student's age: " + s1.getAge());</code></p>
</li>
<li><p>This line calls the <code>getAge</code>method on the <code>student</code>object. The <code>getAge</code>method returns the value of the private <code>age</code>field, which is then printed to the console.</p>
</li>
</ul>
</li>
</ol>
<ol>
<li><p><strong>Data Hiding</strong> : The <code>age</code> field is private, so it cannot be accessed directly from outside the <code>Student</code>class. This means the internal state of the <code>Student</code>is hidden from the outside world.</p>
</li>
<li><p><strong>Controlled Access</strong> : We provide public methods <code>getAge()</code> and <code>setAge(int age)</code> to access and modify the <code>age</code> field. This allows us to add validation logic inside the <code>setAge()</code> method to ensure that the age cannot be set to a negative value.</p>
</li>
</ol>
<h3 id="heading-why-we-use-encapsulation">Why we use Encapsulation?</h3>
<p>There are several advantages for using Encapsulation;</p>
<ol>
<li><p><mark>Data Protection</mark>: By making fields private, you can prevent external code from changing the state of the object in unexpected ways.</p>
</li>
<li><p><mark>Controlled Access</mark>: By providing public getter and setter methods, you can control how the internal state of an object is accessed and modified. This allows you to add validation, logging, or other logic when the state is changed.</p>
</li>
<li><p><mark>Easy to maintain</mark>: Encapsulation helps to keep the code modular. So that every class can be developed, tested and maintained independently.</p>
</li>
<li><p><mark>Resuability</mark>: It encourages the creation of reusable components. By exposing only the necessary details through public methods, you can create classes that can be reused across different parts of an application.</p>
</li>
</ol>
<h3 id="heading-getter-and-setter-methods">Getter and Setter Methods</h3>
<p>We have already mentioned about the getter and setter methods above. So now lets understand what are these in detail.</p>
<p>In Java, getter and setter methods are used to access and modify the private fields of a class from outside the class. They are part of the encapsulation concept.</p>
<ul>
<li><p><strong>Getter Method</strong>: This method is used to read or "get" the value of a private field.</p>
</li>
<li><p><strong>Setter Method</strong>: This method is used to update or "set" the value of a private field.</p>
</li>
</ul>
<h3 id="heading-why-we-use-these-getter-and-setter-methods">Why we use these Getter and Setter methods?</h3>
<p>Since fields in a class are often made private to protect them from direct access, getter and setter methods provide a way to access and update these private fields indirectly. This allows for controlled access and modification.</p>
<p>So, let's take the same example from above and explain it again. This will help beginners understand it with more clarity.</p>
<p>Imagine a simple class called <code>Student</code>with a private field <code>name</code>.</p>
<p>Step - 1</p>
<p>Define the class with a private field.</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">Student</span> </span>{
 <span class="hljs-keyword">private</span> String name; <span class="hljs-comment">// private field</span>
}
</code></pre>
<p>Here, <code>name</code> is a private field, meaning it cannot be accessed directly from outside the <code>Student</code>class.</p>
<p>Step - 2</p>
<p>Create setter and getter methods - to access and modify the name field.</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">Student</span></span>{
<span class="hljs-keyword">private</span> String name;

<span class="hljs-comment">//getter method</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> <span class="hljs-comment">// getter and setter are not predefined method names.</span>
  </span>{
   <span class="hljs-keyword">return</span> name;
  }

<span class="hljs-comment">//setter method</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">setName</span><span class="hljs-params">()</span></span>{
    <span class="hljs-keyword">this</span>.name= name
  }
}
</code></pre>
<p>Step -3</p>
<p>Now let's see how can we access and update the name field value in the above 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">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Student s1= <span class="hljs-keyword">new</span> Student();  <span class="hljs-comment">// Create a new Student object</span>

        <span class="hljs-comment">// Set the name using the setter method</span>
        s1.setName(<span class="hljs-string">"Sankarlal"</span>);

        <span class="hljs-comment">// Get the name using the getter method</span>
        System.out.println(<span class="hljs-string">"Student's name: "</span> + s1.getName());  <span class="hljs-comment">// Output: Student's name: Sankarlal</span>
    }
}
</code></pre>
<ol>
<li><p><strong>Setting the Name</strong>:</p>
<ul>
<li><p><code>s1.setName("Sankarlal");</code></p>
</li>
<li><p>This line calls the <code>setName</code> method on the <code>student</code>object, passing "Sankarlal" as an argument. The <code>setName</code> method updates the private <code>name</code> field with this value.</p>
</li>
</ul>
</li>
<li><p><strong>Getting the Name</strong>:</p>
<ul>
<li><p><code>System.out.println("Student's name: " + s1.getName());</code></p>
</li>
<li><p>This line calls the <code>getName</code> method on the <code>student</code>object. The <code>getName</code> method returns the value of the private <code>name</code> field, which is then printed to the console.</p>
</li>
</ul>
</li>
</ol>
<p>I think now you have a good understanding of Encapsulation and how getter and setter methods work.</p>
]]></content:encoded></item><item><title><![CDATA[Mastering Dates: A Comprehensive Guide to Handling Dates in JavaScript]]></title><description><![CDATA[When working on any project, you will encounter various situations where you need to utilize dates in different forms. Sometimes, you need to retrieve the current date, while other times you may have to schedule a process for a specific time. Additio...]]></description><link>https://blog.sankarlal.in/mastering-dates-a-comprehensive-guide-to-handling-dates-in-javascript</link><guid isPermaLink="true">https://blog.sankarlal.in/mastering-dates-a-comprehensive-guide-to-handling-dates-in-javascript</guid><category><![CDATA[javascript essentials]]></category><category><![CDATA[date.now]]></category><category><![CDATA[date in js]]></category><category><![CDATA[dates]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[sankarlal]]></category><category><![CDATA[js]]></category><category><![CDATA[Computer Science]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[coding]]></category><category><![CDATA[mustread]]></category><dc:creator><![CDATA[J B Sankarlal]]></dc:creator><pubDate>Fri, 23 Feb 2024 10:09:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717312701074/6aaa58cf-1041-4ee0-be1f-ca5541de8228.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When working on any project, you will encounter various situations where you need to utilize dates in different forms. Sometimes, you need to retrieve the current date, while other times you may have to schedule a process for a specific time. Additionally, you might need to sort or retrieve data from a database using time or date as a filter. This short article aims to provide an overview of handling dates in JavaScript, particularly useful for beginners. Let's get started.</p>
<h3 id="heading-current-date-and-time">Current Date and Time</h3>
<p>So the first thing is how to get the current date and time using JavaScript? It's very simple as we have a built-in Date object for that- "<strong>new Date()</strong>". We only need to call it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()
<span class="hljs-built_in">console</span>.log(currentDate)

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">2024</span><span class="hljs-number">-02</span><span class="hljs-number">-19</span>T16:<span class="hljs-number">32</span>:<span class="hljs-number">30.069</span>Z
</code></pre>
<h3 id="heading-current-year">Current Year</h3>
<p>Next is how to get the current year. For that we have a method which can be used along with Date object. It is "<strong>getFullYear()</strong>".</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getFullYear();
<span class="hljs-built_in">console</span>.log(currentDate);

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">2024</span>
</code></pre>
<h3 id="heading-current-month0-11">Current Month(0-11)</h3>
<p>To fetch the current month we have a built-in method called "<strong>getMonth()</strong>", which can be used with Date object. Here you should know that this will return the present month index number and it starts with 0 for "January" and ends with 11 for "December". In real time it's February now, so if I use this method it will return 1, and if i have used this in last month, which is January, then it would have returned 0, and 2 for March and it goes on.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMonth();
<span class="hljs-built_in">console</span>.log(currentDate);

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">1</span> <span class="hljs-comment">// as it is February</span>
</code></pre>
<p>If you want to return the current month in words, you can use like this;</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> months = [
 <span class="hljs-string">"January"</span>, <span class="hljs-string">"February"</span>, <span class="hljs-string">"March"</span>, <span class="hljs-string">"April"</span>, <span class="hljs-string">"May"</span>, <span class="hljs-string">"June"</span>,
  <span class="hljs-string">"July"</span>, <span class="hljs-string">"August"</span>, <span class="hljs-string">"September"</span>, <span class="hljs-string">"October"</span>, <span class="hljs-string">"November"</span>, <span class="hljs-string">"December"</span>
]

<span class="hljs-keyword">const</span> currentMonth = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMonth();
<span class="hljs-keyword">const</span> monthInWords = months[currentMonth];
<span class="hljs-built_in">console</span>.log(monthInWords);

<span class="hljs-comment">//OUTPUT</span>
February
</code></pre>
<h3 id="heading-current-date1-31">Current Date(1- 31)</h3>
<p>If you want to get just the current day in number, you can use the "<strong>getDate()"</strong> method along with Date object. You will get a value between 1-31 based on which date is today.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getDate();
<span class="hljs-built_in">console</span>.log(currentDate);

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">19</span>
</code></pre>
<h3 id="heading-current-day-of-the-week0-6">Current Day of the Week(0-6)</h3>
<p>For that we use "<strong>getDay()</strong>" method. This will return a number between 0 to 6, where 0 indicates "Sunday" and 6 indicates "Saturday".</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getDate();
<span class="hljs-built_in">console</span>.log(currentDate);

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">1</span> <span class="hljs-comment">// as today is Monday</span>
</code></pre>
<h3 id="heading-hours-minutes-seconds-and-milliseconds">Hours, Minutes, Seconds and Milliseconds</h3>
<p>For fetching these you can use these methods respectively; <strong>getHours(), getMinutes(), getSeconds(), getMilliseconds():</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
<span class="hljs-built_in">console</span>.log(currentDate);

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">22</span>
</code></pre>
<h3 id="heading-what-is-datenow">What is Date.now( ) ?</h3>
<p>It is a static method of Date object. It returns current time in milliseconds. It actually returns number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC, according to the system clock.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-built_in">Date</span>.now();
<span class="hljs-built_in">console</span>.log(currentDate);

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">1708363554396</span>
</code></pre>
<p>Usage: This provides a high-resolution timestamp that is useful for precise timing calculations.</p>
<h3 id="heading-dateutc-important">Date.UTC( ) - Important</h3>
<p>When dealing with dates, sometimes we may encounter inaccuracies in time due to changes in local time zones. In such cases, you can use "<strong>Date.UTC( )</strong>" to retrieve the exact time, ensuring precision and consistency regardless of local time zone variations.</p>
<p>Before looking at the you need to understand what is UTC. You all might have heard about <strong>GMT(Greenwich Mean Time)</strong>. It is a time standard that is often used as a reference point for timekeeping.</p>
<ul>
<li><p>It is based on the mean solar time at the Prime Meridian (0° longitude) located in Greenwich, London, UK.</p>
</li>
<li><p>Historically, GMT was used as the international civil time standard before being replaced by <strong>Coordinated Universal Time (UTC)</strong>.</p>
</li>
</ul>
<p>So, UTC(Coordinated Universal Time) is a time standard that is essentially a successor to GMT. It is more precisely defined and does not vary with Earth's irregular rotation.</p>
<p>Now, let's write a code to fetch the first date of the current month using "<strong>Date.UTC()</strong>".</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> firstDateOfMonth = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-built_in">Date</span>.UTC(currentDate.getFullYear(), currentDate.getMonth(), <span class="hljs-number">1</span>));
<span class="hljs-built_in">console</span>.log(firstDateOfMonth);


<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">2024</span><span class="hljs-number">-02</span><span class="hljs-number">-01</span>T00:<span class="hljs-number">00</span>:<span class="hljs-number">00.000</span>Z
</code></pre>
<p>and if i write the same code without Date.UTC( ) for getting the first date of the month, then the output is like this.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> firstDateOfMonth = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(currentDate.getFullYear(), currentDate.getMonth(), <span class="hljs-number">1</span>);
<span class="hljs-built_in">console</span>.log(firstDateOfMonth);

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">2024</span><span class="hljs-number">-01</span><span class="hljs-number">-31</span>T18:<span class="hljs-number">30</span>:<span class="hljs-number">00.000</span>Z
</code></pre>
<p>There is a difference by some hours between two outputs.</p>
<h3 id="heading-formatting-dates">Formatting Dates</h3>
<p>This is one of the most common requirements in almost all applications. When we fetch dates using the <code>Date</code> object, they typically come in the format 'YYYY-MM-DDTHH:mm:ss.sssZ'. However, in the user interface (UI) of our application, we often need to display dates in a more readable format. To achieve this, we can use date formatting.</p>
<ol>
<li><h3 id="heading-tolocaledatestring"><strong>toLocaleDateString( )</strong></h3>
<p> If you want dates in this format "Monday, February 19, 2024" instead of "2024-02-19T16:32:30.069Z", we can use "<strong>toLocaleDateString( )</strong>" method. So, let's see how it works.</p>
<p> So, in short it provides a way to format date according to the locale(<em>refers to a set of parameters that define the user's language, region, and cultural preferences in computing and software applications</em>) of the user's browser.</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-comment">//SYNTAX</span>

<span class="hljs-keyword">const</span> formattedDate = date.toLocaleDateString(locale, options);
</code></pre>
<ul>
<li><p><code>locale</code>: It's optional. It's a string representing the locale used for formatting dates (e.g., "<strong>en-US</strong>" for <strong>English</strong> (United States), "<strong>fr-FR</strong>" for <strong>French</strong> (France)).</p>
</li>
<li><p><code>options</code>: It's also optional. It's an object containing options for formatting the date, such as <code>weekday</code>, <code>year</code>, <code>month</code>, <code>day</code>, <code>hour</code>, <code>minute</code>, <code>second</code>, <code>timeZone</code>, etc.</p>
</li>
</ul>
<p>Now let's go in detail with examples.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> dateFormatted = currentDate.toLocaleDateString(<span class="hljs-string">"en-US"</span>, {
  <span class="hljs-attr">weekday</span>: <span class="hljs-string">"long"</span>,
  <span class="hljs-attr">day</span>: <span class="hljs-string">"numeric"</span>,
  <span class="hljs-attr">month</span>: <span class="hljs-string">"long"</span>,
  <span class="hljs-attr">year</span>: <span class="hljs-string">"numeric"</span>,
});
<span class="hljs-built_in">console</span>.log(dateFormatted);

<span class="hljs-comment">//OUTPUT</span>
Monday, February <span class="hljs-number">19</span>, <span class="hljs-number">2024</span>
</code></pre>
<ol>
<li><h3 id="heading-momentjs"><strong>moment.js</strong></h3>
<p> This is a javaScript library which can be used for parsing, validating, manipulating, and formatting dates.</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-comment">//Before using Install it in the terminal using the following command</span>
npm install moment

<span class="hljs-comment">// AND INCLUDE USING moment.js</span>
<span class="hljs-keyword">const</span> moment = <span class="hljs-built_in">require</span>(<span class="hljs-string">'moment'</span>); <span class="hljs-comment">// this is for Node.js</span>
</code></pre>
<p>Now, let's look at an example how we can format dates using moment.js</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> moment = <span class="hljs-built_in">require</span>(<span class="hljs-string">"moment"</span>);
<span class="hljs-keyword">const</span> formattedDate = moment().format(<span class="hljs-string">"MMMM Do YYYY, h:mm:ss a"</span>);
<span class="hljs-built_in">console</span>.log(formattedDate);

<span class="hljs-comment">//OUTPUT</span>
February <span class="hljs-number">19</span>th <span class="hljs-number">2024</span>, <span class="hljs-number">1</span>:<span class="hljs-number">16</span>:<span class="hljs-number">23</span> pm
</code></pre>
<p>Moment.js allows for extensive customization of date formatting using format strings. For example:</p>
<ul>
<li><p><code>"MMMM"</code>: Month in full name</p>
</li>
<li><p><code>"Do"</code>: Day of the month with ordinal (e.g., "1st", "2nd", "3rd", etc.)</p>
</li>
<li><p><code>"YYYY"</code>: Full year</p>
</li>
<li><p><code>"h:mm:ss a"</code>: Hour, minutes, seconds, and AM/PM specification.</p>
</li>
</ul>
<p><strong>Time Zone Customization</strong></p>
<p>In moment.js time zones can be customized using "<strong>moment-timezone</strong>" extension. This extension allows you to work with time zones and convert dates between different time zones.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//Before using Install it in the terminal using the following command</span>
npm install moment moment-timezone
</code></pre>
<p>Let's look at the syntax with an example</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> moment = <span class="hljs-built_in">require</span>(<span class="hljs-string">'moment'</span>);
<span class="hljs-built_in">require</span>(<span class="hljs-string">'moment-timezone'</span>);

<span class="hljs-comment">// Create a Moment.js object</span>
<span class="hljs-keyword">const</span> date = moment();

<span class="hljs-comment">// Display the current date and time in a specific time zone</span>
<span class="hljs-keyword">const</span> formattedDate = date.tz(<span class="hljs-string">'America/New_York'</span>).format(<span class="hljs-string">'YYYY-MM-DD HH:mm:ss'</span>);

<span class="hljs-built_in">console</span>.log(formattedDate);

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">2024</span><span class="hljs-number">-02</span><span class="hljs-number">-19</span> <span class="hljs-number">03</span>:<span class="hljs-number">29</span>:<span class="hljs-number">48</span>
</code></pre>
<h3 id="heading-iso-date">ISO Date</h3>
<p>The ISO 8601 format is an internationally accepted standard for representing dates and times in a way that is easily readable and sortable. It was developed by the International Organization for Standardization (ISO).</p>
<p>The basic format for dates and times in ISO 8601 is as follows:</p>
<ul>
<li><p><strong>Date</strong>: <code>YYYY-MM-DD</code> (e.g., 2024-02-19)</p>
</li>
<li><p><strong>Time</strong>: <code>HH:mm:ss</code> (e.g., 12:30:00)</p>
</li>
<li><p><strong>Combined Date and Time</strong>: <code>YYYY-MM-DDTHH:mm:ss</code> (e.g., 2024-02-19T12:30:00)</p>
</li>
</ul>
<p>The extended format allows for more precision and includes additional components:</p>
<ul>
<li><p><strong>Date</strong>: <code>YYYY-MM-DD</code> (e.g., 2024-02-19)</p>
</li>
<li><p><strong>Time</strong>: <code>HH:mm:ss.sss</code> (e.g., 12:30:00.000)</p>
</li>
<li><p><strong>Time Zone Offset</strong>: <code>±HH:mm</code> or <code>±HHmm</code> (e.g., +05:00, -0800)</p>
</li>
<li><p><strong>Combined Date and Time with Time Zone Offset</strong>: <code>YYYY-MM-DDTHH:mm:ss.sssZ±HH:mm</code> (e.g., 2024-02-19T12:30:00.000Z).</p>
</li>
</ul>
<p>So, in short this is a standardized and efficient way to represent dates.</p>
<p><strong>Converting dates to ISO format.</strong></p>
<p>Sometimes, we need to convert dates into ISO String format in our projects or applications. So for that we use the "<strong>toISOString( )</strong>" method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> date= <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> isoDate = date.toISOString();
<span class="hljs-built_in">console</span>.log(isoDate);

<span class="hljs-comment">//OUTPUT</span>
<span class="hljs-number">2024</span><span class="hljs-number">-02</span><span class="hljs-number">-19</span>T12:<span class="hljs-number">30</span>:<span class="hljs-number">00.000</span>Z
</code></pre>
<p>So these all are the main things I would like to explain in this article related to Dates in JavaScript.</p>
]]></content:encoded></item><item><title><![CDATA[ABSTRACTION - Java OOPs Simplified - Part 5]]></title><description><![CDATA[ABSTRACTION
In the previous articles, we delve deep into the 2 pillars of OOPs, i.e. Inheritance and Polymorphism. In this, we will understand the important things related to another important pillar of OOPs, i.e. Abstraction. So the first question i...]]></description><link>https://blog.sankarlal.in/java-oops-simplified-part-5</link><guid isPermaLink="true">https://blog.sankarlal.in/java-oops-simplified-part-5</guid><category><![CDATA[java oops]]></category><category><![CDATA[abstraction in java]]></category><category><![CDATA[abstraction]]></category><category><![CDATA[Java]]></category><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[OOPS]]></category><dc:creator><![CDATA[J B Sankarlal]]></dc:creator><pubDate>Sat, 13 Jan 2024 09:31:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717326662801/e0f443d8-a755-4388-ac3e-32602242c443.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-abstraction">ABSTRACTION</h2>
<p>In the previous articles, we delve deep into the 2 pillars of OOPs, i.e. Inheritance and Polymorphism. In this, we will understand the important things related to another important pillar of OOPs, i.e. Abstraction. So the first question is;</p>
<h3 id="heading-whats-meant-by-abstraction-in-java"><strong>What's meant by Abstraction in Java?</strong></h3>
<p>It is a concept in OOPs, that allows us <strong>to hide the complex implementation and show only the essential features of an object or class.</strong></p>
<p>Now if you read this, and go for a real-time example, you will get confused. In many places on the internet, we can see examples of Facebook or WhatsApp, and it says abstraction is like hiding the codes or implementation and just showing what is needed.</p>
<p>So, here there is a possibility that beginners may get confused, they may think that if abstraction is not there we may be able to see the backend codes of applications like Facebook or WhatsApp. But this is not that, abstraction has nothing to do with the end-users of these apps, instead, this is a concept to help the programmers to reduce code complexity and thereby improve the code readability.</p>
<p>Now let's look at a code-based example of Abstraction. Here I'm gonna show you what actually abstraction help us to achieve. We are going to see both the <strong>normal method</strong> implementation and <strong>abstract method</strong> implementation.</p>
<pre><code class="lang-java"><span class="hljs-comment">// NORMAL CLASS</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-comment">// Normal method with implementation</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSound</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Dog barks"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Animal a1 = <span class="hljs-keyword">new</span> Animal(); 
        <span class="hljs-comment">// Call the normal method</span>
        a1.makeSound(); <span class="hljs-comment">// Output: Dog barks</span>
    }
}
</code></pre>
<p>The code provided above demonstrates the implementation of a normal class. In the <code>Animal</code> class, there is a method called <code>makeSound()</code> which has an implementation (means it actually explains what that function do, here it has a statement to print "Dog barks"). In the <code>Main</code> class, an instance <code>a1</code> of the <code>Animal</code> class is created, and we call the <code>makeSound()</code> method using <code>a1.makeSound()</code>.</p>
<p>Now let's have a look at the implementation of an abstract class.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Abstract class</span>
<span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-comment">// Abstract method (no implementation)</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSound</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-comment">// Concrete subclass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-comment">// Implementing the abstract method</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSound</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Dog barks"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create an instance of Dog</span>
        Dog d1 = <span class="hljs-keyword">new</span> Dog();

        <span class="hljs-comment">// Call the abstract method</span>
        d1.makeSound(); <span class="hljs-comment">// Output: Dog barks</span>
    }
}
</code></pre>
<p>"In the example provided above, the <code>Animal</code> class is declared as abstract using the <code>abstract</code> keyword. Inside the abstract class, you can observe the presence of an abstract method, <code>makeSound()</code>.</p>
<p>Since this method is abstract, it lacks a direct implementation. It is merely declared without a concrete implementation (without any body). This demonstrates the concept of hiding the code implementation, as mentioned earlier.</p>
<p>In the code, a normal class named <code>Dog</code> is created, and the <code>makeSound()</code> method is implemented within it. It's because, you cannot create an instance of an abstract class directly, which means that <code>Animal a1 = new Animal()</code> is not possible.</p>
<p>Instead, we extend a normal class to create a subclass, as shown in the above program. You can see that in the code, an instance of the <code>Dog</code> class is created using <code>Dog d1 = new Dog()</code>. This instance is then used to call the <code>makeSound()</code> method."</p>
<h3 id="heading-advantages-of-abstraction"><strong>Advantages of Abstraction</strong></h3>
<ol>
<li><p>It improves code readability.</p>
</li>
<li><p>It hides the code complexity, by declaring methods as abstract.</p>
</li>
<li><p>It supports code reusability, as multiple classes can implement the same interface or extend the same abstract class.</p>
</li>
<li><p>It simplifies the code by breaking it into smaller and manageable parts.</p>
</li>
</ol>
<p>Now, we have an idea about the concept of Abstraction in OOPs, now lets have a close look at the Abstract methods.</p>
<h3 id="heading-what-is-an-abstract-method"><strong>What is an Abstract Method?</strong></h3>
<p>Now we have an idea about abstract class as we have gone through the concept of abstraction. So, abstract method is a method which is declared in a class, but it doesn't have any instructions or details on how it should work, so in short, a method without a body.</p>
<p>It doesn't have an implementation, it only contains the method declaration.</p>
<p>It is also important to note that you have to use the keyword <code>abstract</code> before any abstract method.</p>
<p><strong>NB</strong>: When you have an abstract method in a class, you can't create an object directly from that class. You have to create a new class that "extends" the abstract class(subclass) and provides the implementation of your abstract method in that new class(subclass).</p>
<p>So let's see how to create an abstract method as per above instructions;</p>
<pre><code class="lang-java"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cars</span> </span>{
    <span class="hljs-comment">// Abstract method without implementation</span>
    <span class="hljs-function"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Ferrrari</span><span class="hljs-params">()</span></span>;

    <span class="hljs-comment">// Regular method with an implementation</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Audi</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"This is an Audi car"</span>);
    }
}
</code></pre>
<p>Now if you want to implement this we have to create a subclass extending the main class called <code>Cars</code> . Let's see how to implement this abstract class called <code>Ferrari</code> .</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SUV</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Cars</span> </span>{
    <span class="hljs-comment">// Implementation of the abstract method</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Ferrari</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"This is the red Ferrari"</span>);
    }
}
</code></pre>
<p>So here we have created a subclass called <code>SUV</code> and implemented the abstract method <code>Ferrari()</code> . So this is how we implement an abstract method.</p>
<p>Now if you want to create more subclasses and implement the method, you can do that. So let's create another subclass <code>Sedan</code> and implement the same abstract method <code>Ferrari()</code> .</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Sedan</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Cars</span> </span>{
    <span class="hljs-comment">// Implementation of the abstract method</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Ferrari</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"This is the New Sedan model of Ferrari"</span>);
    }
}
</code></pre>
<p>Let's have a look at the implementation of 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">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Creating objects of the concrete classes</span>
        SUV theSuv = <span class="hljs-keyword">new</span> SUV();
        Sedan theSedan = <span class="hljs-keyword">new</span> Sedan();

        <span class="hljs-comment">// Calling the abstract method and the regular method</span>
        theSuv.Ferrari();  <span class="hljs-comment">// Output: This is the red Ferrari</span>
        theSuv.Audi();      <span class="hljs-comment">// Output: This is an Audi car.</span>

        theSedan.Ferrari();  <span class="hljs-comment">// Output: This is the New Sedan model of Ferrari</span>
        theSedan.Audi();      <span class="hljs-comment">// Output: This is an Audi car</span>
    }
}
</code></pre>
<p>In the <code>Main</code> class, objects of both <code>SUV</code> and <code>Sedan</code> are created and used to call both the abstract method and the regular method.</p>
<h3 id="heading-how-to-achieve-abstraction-in-java">How to achieve Abstraction in Java?</h3>
<p>There are mainly 2 ways to achieve abstraction in Java;</p>
<ol>
<li><p>using Abstract Class(0 to 100% abstraction).</p>
</li>
<li><p>using Interfaces.</p>
</li>
</ol>
<p>You already saw how can we achieve abstraction using an abstract class. So the main things to be noted while creating an abstract class is that you have to use an <strong>abstract</strong> keyword. You can use both abstract and non-abstract methods in an abstract class. It cannot be instantiated. Also you need to extend a subclass for implementing an abstract method in an abstract class.</p>
<p>So now let's see how to achieve abstraction using Interfaces.</p>
<h3 id="heading-abstraction-using-interfaces">Abstraction using Interfaces</h3>
<p><strong>What is an interface?</strong></p>
<p>In simple words we can say its a set of rules. It's more like an agreement, that is if you want to be part of that agreement you must be ready to follow the set of rules provided in the agreement.</p>
<p>In interfaces, all the methods are abstract by default which means in interface we can only declare the methods, there will be no definitions or implementations for that method within the interface.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">drive</span><span class="hljs-params">()</span></span>;  <span class="hljs-comment">// Just says: "Hey, you must have a drive() method!"</span>
}
</code></pre>
<p>So the next question is, then how will we implement these abstract methods in interfaces?</p>
<p>So, for implementing the methods in an interface, we need to define a class using the keyword '<strong>implements</strong>' and then implement those methods which we declare in the interfaces inside that class.</p>
<pre><code class="lang-java">
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">drive</span><span class="hljs-params">()</span></span>;  
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Road</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Vehicles</span> </span>{
    <span class="hljs-comment">// We HAVE to provide the implementation for draw() because we said we implement Drawable</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drive</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Always Drive Carefully"</span>);
    }
}
</code></pre>
<p>So, this is how we use interfaces to implement abstraction. You can take the example of implementing multiple inheritances in Java as an illustration of interfaces using the concept of abstraction to achieve multiple inheritance in Java.</p>
<h3 id="heading-is-it-necessary-to-have-at-least-one-abstract-method-in-an-abstract-class">Is it necessary to have at least one abstract method in an Abstract Class?</h3>
<p>No, its is not necessary that an abstract class should contain at least one abstract method. An abstract class can exist without any abstract methods. Abstract classes can also contain concrete methods (methods with a complete implementation), fields, and constructors.</p>
<p>An abstract class provides 0% to 100% abstraction, which means that it can either contain only non-abstract methods (concrete methods), resulting in 0% abstraction, or it can consist entirely of abstract methods, achieving 100% abstraction. It is also possible for an abstract class to contain both abstract and non-abstract methods simultaneously.</p>
]]></content:encoded></item><item><title><![CDATA[POLYMORPHISM - Java OOPs Simplified - Part 4]]></title><description><![CDATA[POLYMORPHISM
Polymorphism is one of the 4 major pillars of OOPs. The other three are Inheritance, Abstraction and Encapsulation.
"Polymorphism" is derived from 2 Greek words, where 'poly' means "many" and 'morphs' means "forms", so in turn polymorphi...]]></description><link>https://blog.sankarlal.in/java-oops-simplified-part-4</link><guid isPermaLink="true">https://blog.sankarlal.in/java-oops-simplified-part-4</guid><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[OOPS]]></category><category><![CDATA[polymorphism]]></category><category><![CDATA[method OVERLOADING]]></category><category><![CDATA[METHOD OVERRIDING]]></category><dc:creator><![CDATA[J B Sankarlal]]></dc:creator><pubDate>Wed, 11 Oct 2023 19:31:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717326643744/9c0966d6-6a1c-4e29-95a4-45e830d267cf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-polymorphism">POLYMORPHISM</h3>
<p>Polymorphism is one of the 4 major pillars of OOPs. The other three are Inheritance, Abstraction and Encapsulation.</p>
<p>"Polymorphism" is derived from 2 Greek words, where '<strong>poly</strong>' means "many" and '<strong>morphs</strong>' means "forms", so in turn polymorphism means "<strong>many forms</strong>".</p>
<p>So in Java, it's the way of performing a task in different ways, i.e., the same object or method can perform different things in different scenarios.</p>
<p>Now, let me take an example to explain it in a much easier way. The most simple and commonly stated example is that of Shapes. <em>Imagine you have a drawing program that can draw different shapes like circles, squares, and triangles. Each shape can be drawn on the screen, but they have their unique ways of drawing.</em></p>
<p>So let's see how this works in code.</p>
<pre><code class="lang-java"><span class="hljs-comment">// this is a common Shape interface</span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Shape</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">draw</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-comment">// Let's create specific shape classes that implement Shape</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Triangle</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Shape</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">draw</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Drawing a Triangle"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Oval</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Shape</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">draw</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Drawing a Oval"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rectangle</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Shape</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">draw</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Drawing a Rectangle"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Im just creating an array of different shapes</span>
        Shape[] shapes = <span class="hljs-keyword">new</span> Shape[<span class="hljs-number">3</span>];
        shapes[<span class="hljs-number">0</span>] = <span class="hljs-keyword">new</span> Triangle();
        shapes[<span class="hljs-number">1</span>] = <span class="hljs-keyword">new</span> Oval();
        shapes[<span class="hljs-number">2</span>] = <span class="hljs-keyword">new</span> Rectangle();

      <span class="hljs-comment">// here we are using polymorphism to draw different shapes</span>
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; shapes.length; i++) {
         Shape shape = shapes[i];
         shape.draw();
       }
    }
}
</code></pre>
<p>So if I explain the above example;</p>
<ol>
<li><p>So here we have a common interface <code>Shape</code> with a method <code>draw()</code>.</p>
</li>
<li><p>We create specific shape classes (<code>Triangle</code>, <code>Oval</code>, <code>Rectangle</code>) that implements the <code>Shape</code> interface and provide their unique <code>draw()</code> implementations.</p>
</li>
<li><p>In the <code>Main</code> class, we create an array of different shapes, each instantiated as a different type of shape (polymorphism).</p>
</li>
<li><p>We use a for loop to call the <code>draw()</code> method on each shape, and even though we're using the same method name, each shape draws itself the respective shape based on its specific implementation.</p>
</li>
</ol>
<p>So now you have got an idea about the purpose of Polymorphism. Now let's look at the different ways to achieve this.</p>
<ol>
<li><p>Method Overloading</p>
</li>
<li><p>Method Overriding</p>
</li>
</ol>
<h3 id="heading-method-overloading">Method Overloading</h3>
<p>In method overloading, we can use <strong>the method with the same name but different parameters within a single class</strong>. So in one class, you can have many methods with the same name but different types or different numbers of parameters.</p>
<p>It is also called compile time polymorphism because in the compile time java determines which method to be called based on the number or type of arguments used for method calling.</p>
<p><strong>NB:</strong> <em>Parameters of a method is also called method signature.</em></p>
<p><strong>NB</strong>: <em>Return type is not considered while we overload a method, which means 2 methods within a class can have the same or different return types.</em></p>
<p><strong>NB</strong>: <em>Minimum number of classes required to overload a method is 1.</em></p>
<p>Let's now look at a simple example of method overloading in Java.</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">Calculator</span> </span>{
    <span class="hljs-comment">// a method to add two numbers</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
        <span class="hljs-keyword">return</span> a + b;
    }

    <span class="hljs-comment">// a method to add three numbers</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b, <span class="hljs-keyword">int</span> c)</span> </span>{
        <span class="hljs-keyword">return</span> a + b + c;
    }

    <span class="hljs-comment">// a method to add two double type numbers</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">double</span> a, <span class="hljs-keyword">double</span> b)</span> </span>{
        <span class="hljs-keyword">return</span> a + b;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Calculator c1 = <span class="hljs-keyword">new</span> Calculator();

        <span class="hljs-keyword">int</span> result1 = c1.add(<span class="hljs-number">7</span>, <span class="hljs-number">11</span>);
        <span class="hljs-keyword">int</span> result2 = c2.add(<span class="hljs-number">4</span>, <span class="hljs-number">3</span>, <span class="hljs-number">9</span>);
        <span class="hljs-keyword">double</span> result3 = c3..add(<span class="hljs-number">6.5</span>, <span class="hljs-number">1.9</span>);

        System.out.println(<span class="hljs-string">"method1= "</span> + result1); <span class="hljs-comment">// output: method1= 18</span>
        System.out.println(<span class="hljs-string">"method2= "</span> + result2); <span class="hljs-comment">// output: method1= 16</span>
        System.out.println(<span class="hljs-string">"method3= "</span> + result3); <span class="hljs-comment">// output: method1= 8.4</span>
    }
}
</code></pre>
<p>In the above example, the class <code>Calculator</code> used the method with the name <code>add</code> more than once within the class with different numbers and different types of parameters.</p>
<p>If you look at the method you can see an object with name c1 is created and it is used to invoke the methods. Also, it's very important to note that, you have to send the arguments matching the parameters when we call those methods. If you provide arguments of incorrect type or number it will result in a "compilation error".</p>
<p>But if you look at the return type we have used the same as well as different return types. So it's clear that return type is not important in method overloading.</p>
<h3 id="heading-method-overriding">Method Overriding</h3>
<p>In method overriding we can use the method with the same name and the same parameters in different classes. So it allows the child class to provide a specific implementation of a method that is already defined in the parent class.</p>
<p>It is important to note that when the child class overrides the method, it provides a new implementation for that method with the same name, parameter and return type.</p>
<p>It is also an example of rum time polymorphism.</p>
<p>NB: <strong>For overriding, we require at least 2 classes.</strong></p>
<p>NB: The <strong>child class cannot use more restrictive access modifiers than the parent class</strong>, which means if the parent class method is public, then child class method should be either public or protected. It cannot be "private".</p>
<p>NB: The <strong>overriding method should have the same method name, parameters and return types.</strong></p>
<p>Now let's have a look at an example of overriding.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ParentCalculator</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
        <span class="hljs-keyword">return</span> a + b;
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChildCalculator</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ParentCalculator</span> </span>{
    <span class="hljs-comment">// Method overriding for add</span>
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
        <span class="hljs-keyword">return</span> a + b + <span class="hljs-number">10</span>; <span class="hljs-comment">// Adds 10 more than the base class, </span>
                           <span class="hljs-comment">// because we can make changes only in this portion.</span>
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        ParentCalculator c1 = <span class="hljs-keyword">new</span> ParentCalculator();
        ChildCalculator c2 = <span class="hljs-keyword">new</span> ChildCalculator();

        <span class="hljs-keyword">int</span> result1 = c1.add(<span class="hljs-number">7</span>, <span class="hljs-number">11</span>);         <span class="hljs-comment">// Calls the base class method</span>
        <span class="hljs-keyword">int</span> result2 = c2.add(<span class="hljs-number">4</span>, <span class="hljs-number">16</span>);         <span class="hljs-comment">// Calls the overridden method</span>

        System.out.println(<span class="hljs-string">"Result1: "</span> + result1); <span class="hljs-comment">// Result1: 18</span>
        System.out.println(<span class="hljs-string">"Result2: "</span> + result2); <span class="hljs-comment">// Result2: 30</span>
    }
}
</code></pre>
<p>In this example, we have a <code>ParentCalculator</code> class with an <code>add</code> a method that adds two numbers. The <code>ChildCalculator</code> class extends <code>ParentCalculator</code> and overrides the <code>add</code> a method to add '2' to the result.</p>
<p>When we create instances of <code>ParentCalculator</code> and <code>ChildCalculator</code> and call the <code>add</code> method, you can see how method overriding works.</p>
<p>One of the important questions is that is it possible to override a static method. And the answer is "NO", it's <strong>not possible to override a static method</strong> as it is bound by a class. Like that <strong>we cannot override a main method</strong>. Because it's a static method.</p>
<p>So this is how method overloading and method overriding work in Java.</p>
]]></content:encoded></item><item><title><![CDATA[Multiple Inheritance, Hybrid Inheritance - Java OOPs Simplified - Part 3]]></title><description><![CDATA[Multiple Inheritance
Java does not support multiple inheritance of classes, where a class inherits from more than one class. However, it supports multiple inheritance through interfaces.

Attempting to inherit a child class from two parent classes is...]]></description><link>https://blog.sankarlal.in/java-oops-simplified-part-3</link><guid isPermaLink="true">https://blog.sankarlal.in/java-oops-simplified-part-3</guid><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[inheritance]]></category><category><![CDATA[Java]]></category><category><![CDATA[OOPS]]></category><category><![CDATA[sankarlal]]></category><dc:creator><![CDATA[J B Sankarlal]]></dc:creator><pubDate>Sat, 07 Oct 2023 10:31:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717326622200/f0711b3b-c82c-4629-aec2-447a33da66b6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-multiple-inheritance">Multiple Inheritance</h3>
<p>Java does not support multiple inheritance of classes, where a class inherits from more than one class. However, it supports multiple inheritance through interfaces.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696661204558/7910a1cb-de22-4109-be3d-c8e06d8bf2ec.png" alt class="image--center mx-auto" /></p>
<p>Attempting to inherit a child class from two parent classes is not allowed in Java due to potential ambiguity for the compiler.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Class1</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span></span>{
        System.out.println(<span class="hljs-string">"Hello"</span>);
}
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Class2</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span></span>{
       System.out.println(<span class="hljs-string">"Hi"</span>);
}
}

<span class="hljs-comment">// This would result in a compilation error because it tries to inherit from both Class1 and Class2.</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Class1</span>, <span class="hljs-title">Class2</span> </span>{
    <span class="hljs-comment">// MyClass code</span>
}
</code></pre>
<p>For instance, consider two parent classes, Parent Class 1 and Parent Class 2, both containing a method named "void display()."</p>
<p>When you call this method on an object of the child class, the compiler faces a difficult situation in determining which version of "void display()" to execute, leading to confusion and, therefore, Java prohibits inheriting from multiple parent classes simultaneously.</p>
<p>So how can we solve this issue? That's where Interface comes into play. Using interfaces we can easily resolve this issue.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696661708420/8ed6e6d2-e281-4ac2-94ed-185394abf7af.png" alt class="image--center mx-auto" /></p>
<p><strong>So the next question is why there is no ambiguity for the compiler when we use Interfaces instead of Classes?</strong></p>
<p>The answer to this is straightforward: <strong>in interfaces, all methods are abstract by default, meaning they are declared without any method body.</strong> To illustrate this concept, let me provide you with an example to clear all confusion.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Define two interfaces</span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Interface1</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Interface2</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-comment">// Implement the interfaces in a class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Interface1</span>, <span class="hljs-title">Interface2</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Hello"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create an object of the class</span>
        MyClass myObj = <span class="hljs-keyword">new</span> MyClass();

        <span class="hljs-comment">// Call methods from the implemented interfaces</span>
        myObj.display();
    }
}
</code></pre>
<p>In this example:</p>
<ol>
<li><p>We define two interfaces, <code>Interface1</code> and <code>Interface 2</code>, each with a single abstract method.</p>
</li>
<li><p>We create a class <code>MyClass</code> that implements both <code>Interface1</code> and <code>Interface2</code>.</p>
</li>
<li><p>Inside <code>MyClass</code>, we provide implementations for the methods defined in both interfaces. Here since both methods are the same, we only need to implement the method once.</p>
</li>
<li><p>In the <code>Main</code> class, we create an object of <code>MyClass</code> and call the methods from both interfaces.</p>
</li>
</ol>
<p>This demonstrates that a class can implement multiple interfaces in Java. Thus there won't be any ambiguity for the compiler here.</p>
<p><strong>NB</strong>: If the parent classes have methods with different names, then you would need to provide the method implementations for both methods inside <code>MyClass</code>, just as we did for the method <code>void display().</code></p>
<p><strong>NB</strong>: <strong><em>Interface is also a user-defined data type in Java similar to that of class.</em></strong></p>
<p>Now let's move on to the Hybrid Inheritance.</p>
<h3 id="heading-hybrid-inheritance">Hybrid Inheritance</h3>
<p>It refers to the combination of different types of inheritance within a program.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696665657577/d5c3dc28-2066-45bb-893e-543fa1dcd78d.png" alt class="image--center mx-auto" /></p>
<p>It involves multiple inheritance, along with some other type of inheritance such as single inheritance or multilevel inheritance.</p>
<p>But Java doesn't <strong>directly support</strong> this kind of inheritance as it uses multiple inheritance and this will lead to one of the potential complications called "diamond problem".</p>
<p><em>(The</em> <strong><em>diamond problem</em></strong> <em>refers to a situation where a class inherits from 2 parent classes with a common ancestor)</em></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696669997030/f843c23b-74f8-4527-a6f5-905f43e1876a.png" alt class="image--center mx-auto" /></p>
<p>In Java, we can achieve this form of inheritance by combining a single inheritance of classes and multiple inheritance through interfaces. This will resolve code complexity and ambiguity issues.</p>
<p>Let's look at an example, of how we solve the diamond problem in inheritance using interfaces.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Define a grandparent interface</span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Grandparent</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">grandparentMethod</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-comment">// Define two parent interfaces</span>
<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Parent1</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">parent1Method</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Parent2</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">parent2Method</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-comment">// Implement the grandparent and parent interfaces in a class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Grandparent</span>, <span class="hljs-title">Parent1</span>, <span class="hljs-title">Parent2</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">grandparentMethod</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Grandparent method implementation"</span>);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">parent1Method</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Parent 1 method implementation"</span>);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">parent2Method</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Parent 2 method implementation"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">childMethod</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Child method implementation"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create an object of MyClass</span>
        MyClass myObj = <span class="hljs-keyword">new</span> MyClass();

        <span class="hljs-comment">// Call methods from all interfaces</span>
        myObj.grandparentMethod();
        myObj.parent1Method();
        myObj.parent2Method();
        myObj.childMethod();
    }
}
</code></pre>
<p>In the above code,</p>
<ol>
<li><p>We define a <code>Grandparent</code> interface with one method, <code>grandparentMethod</code>.</p>
</li>
<li><p>We define two parent interfaces, <code>Parent1</code> and <code>Parent2</code>, each with one method.</p>
</li>
<li><p>The <code>MyClass</code> class implements all three interfaces, providing implementations for all methods.</p>
</li>
<li><p>Additionally, we define a <code>childMethod</code> specific to the <code>MyClass</code> class.</p>
</li>
</ol>
<p>While this example does not directly demonstrate hybrid inheritance with multiple classes, it does show a scenario with one grandparent interface and two parent interfaces, which provides a similar structural concept to what you might see in hybrid inheritance situations.</p>
]]></content:encoded></item><item><title><![CDATA[INHERITANCE - Java OOPs Simplified - Part 2]]></title><description><![CDATA[In my prior article, I explained the essential Object-Oriented Programming (OOP) concepts, including Java classes and objects. Now, let's embark on a comprehensive exploration of OOP's four pillars: Inheritance, Polymorphism, Abstraction, and Encapsu...]]></description><link>https://blog.sankarlal.in/java-oops-simplified-part-2</link><guid isPermaLink="true">https://blog.sankarlal.in/java-oops-simplified-part-2</guid><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[Java]]></category><category><![CDATA[inheritance]]></category><category><![CDATA[OOPS]]></category><category><![CDATA[multilevel inheritance]]></category><dc:creator><![CDATA[J B Sankarlal]]></dc:creator><pubDate>Fri, 06 Oct 2023 10:52:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717326596917/7284aedc-602c-43ff-86a5-7832598f5919.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In my prior article, I explained the essential Object-Oriented Programming (OOP) concepts, including Java classes and objects. Now, let's embark on a comprehensive exploration of OOP's four pillars: Inheritance, Polymorphism, Abstraction, and Encapsulation.</p>
<h3 id="heading-inheritance">Inheritance</h3>
<p>So what's meant by Inheritance in Java?</p>
<p>If I take an example from real life, inheritance means a child acquires some characteristics or behaviour of their parents. Right? It's almost the same in the case of Java.</p>
<p>In Java, inheritance is <strong>a mechanism that allows a class to inherit or acquire the properties and behaviour(attributes and methods) of another class</strong>. Here a new class (the child or subclass) can reuse and extend the attributes and methods of an existing class (the parent or superclass).</p>
<h3 id="heading-advantages-of-inheritance">Advantages of Inheritance</h3>
<p><strong>Code reusability</strong>- We don't need to rewrite or duplicate code that already exists in the parent class.</p>
<p><strong>Easy Maintenance</strong>- When we make some changes in the parent class, that will be automatically inherited by all the child classes.</p>
<p><strong>Extensibility</strong>- We can extend the behaviour of the existing child classes by adding new fields and methods or by modifying existing ones.</p>
<p><strong>Consistency</strong>- It provides consistency for the code base, which makes it easier to understand and maintain.</p>
<h3 id="heading-types-of-inheritance-in-java">Types of Inheritance in Java</h3>
<ol>
<li><p>Single Inheritance</p>
</li>
<li><p>Multilevel Inheritance</p>
</li>
<li><p>Hierarchical Inheritance</p>
</li>
</ol>
<p>Java also provide support for other 2 inheritances, i.e. Multiple inheritance and Hybrid Inheritance, but not directly instead it supports it through interfaces.</p>
<h3 id="heading-single-inheritance">Single Inheritance</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696568144753/02ede684-d003-43b1-a69f-60fd4e1cffdf.png" alt class="image--center mx-auto" /></p>
<p>Single inheritance means that a class can inherit from only one superclass. In other words, a subclass can have only one immediate parent class.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent</span> </span>{
  <span class="hljs-comment">// Parent class code</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Parent</span> </span>{
  <span class="hljs-comment">// Child class inherits from Parent</span>
}
</code></pre>
<h3 id="heading-multilevel-inheritance">Multilevel Inheritance</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696573242688/0c3f6da1-fd6c-4627-82a0-1db862aaa5b7.png" alt class="image--center mx-auto" /></p>
<p>Multilevel inheritance occurs when a class inherits from another class, and that class is further inherited by another class. So it's a chain of inheritance.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Grandparent</span> </span>{
  <span class="hljs-comment">// Grandparent class code</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Grandparent</span> </span>{
  <span class="hljs-comment">// Parent class inherits from Grandparent</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Parent</span> </span>{
  <span class="hljs-comment">// Child class inherits from Parent</span>
}
</code></pre>
<h3 id="heading-hierarchical-inheritance">Hierarchical Inheritance</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696575320231/1884aad5-c127-4132-846e-076eb60257bd.png" alt class="image--center mx-auto" /></p>
<p>Hierarchical inheritance happens when multiple classes inherit from a single superclass, which means that multiple child classes will have a common parent class.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Parent</span> </span>{
  <span class="hljs-comment">// Parent class code</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child1</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Parent</span> </span>{
  <span class="hljs-comment">// Child1 class inherits from Parent</span>
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Child2</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Parent</span> </span>{
  <span class="hljs-comment">// Child2 class inherits from Parent</span>
}
</code></pre>
<p>So these are the 3 types of inheritance supported by Java. Now we have two more, Multiple inheritance and Hybrid Inheritance. One crucial aspect worth noting is multiple inheritance, a concept achieved in Java through the use of interfaces. I will delve into this topic extensively in the upcoming article.</p>
]]></content:encoded></item><item><title><![CDATA[Java OOPs Simplified - Part 1]]></title><description><![CDATA[What is Object Oriented Programming?
It is a programming paradigm based on the concept of "objects".
(So what is meant by a Programming paradigm? These are nothing but different ways or styles in which a given program or programming language can be o...]]></description><link>https://blog.sankarlal.in/java-oops-simplified-part-1</link><guid isPermaLink="true">https://blog.sankarlal.in/java-oops-simplified-part-1</guid><category><![CDATA[Java]]></category><category><![CDATA[OOPS]]></category><category><![CDATA[classes]]></category><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[Objects]]></category><dc:creator><![CDATA[J B Sankarlal]]></dc:creator><pubDate>Thu, 05 Oct 2023 19:28:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717326574599/13a37fe9-f1d9-44f2-9a8a-a4e49ae6fe2d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-object-oriented-programming">What is Object Oriented Programming?</h3>
<p>It is <strong>a programming paradigm</strong> based on the concept of "objects".</p>
<p>(<em>So what is meant by a Programming paradigm? These are nothing but different ways or styles in which a given program or programming language can be organized</em>)</p>
<p>OOPs follow a <strong>bottom-up approach.</strong></p>
<p>(<em>See, in the bottom-up approach we solve smaller problems and then integrate them into a complete solution, whereas in the top-down approach, we break up the problem into smaller parts and then solve it.</em>)</p>
<p>OOPs is based on real-world entities, which means that they just bring, the way we think and conceptualize things into the software design.</p>
<p><strong>C++, Java, Python, C#</strong>... etc. are examples of OOPs based programming languages.</p>
<h3 id="heading-advantages-of-oops">Advantages of OOPs</h3>
<ol>
<li><p><strong>Code Reusability</strong>- Once we write a code, it can be reused multiple times and this is achieved mainly with the help of a key concept called <strong>Inheritance</strong>.</p>
</li>
<li><p><strong>Security</strong>- with the help of <strong>Encapsulation</strong>, we can bind data(attributes) and methods into a single unit called class and can control the access to these using access specifiers like "Private", "Protected", and "Public.</p>
</li>
<li><p><strong>Flexibility</strong>- In Java <strong>Polymorphism</strong> allows us to create multiple classes that can be reused, also it allows us to reuse the methods with "the same name and same parameter" in different classes and "methods with the same name and different parameters" in the same classes. ie. <strong>overriding</strong> &amp; <strong>overloading</strong> respectively.</p>
</li>
<li><p><strong>Improves Readability</strong> - when we use Abstraction, we can create abstract methods, which help in data hiding as well as improve the code readability for the user(here user means a programmer).</p>
</li>
</ol>
<h3 id="heading-disadvantages-of-oops">Disadvantages of OOPs</h3>
<ol>
<li><p><strong>Complexity</strong>- the length of the programs will be larger than the ones written using procedural-oriented programming.</p>
</li>
<li><p><strong>Memory Usage</strong>- Object-oriented programs tend to consume more memory than the procedural-oriented approach.</p>
</li>
<li><p><strong>The overhead of abstraction</strong> - excessive use of abstraction may lead to complex code that is difficult to navigate, in such cases, it will be a challenge for the developer to understand how the data and methods are connected.</p>
</li>
</ol>
<p>So these are all the major advantages and disadvantages of OOPs in Java. While stating the disadvantages I have mentioned procedural-oriented programming. So what is that? How is it different from the object-oriented programming approach? Come let's have a look.</p>
<h3 id="heading-oops-vs-popsprocedural-oriented-programming">OOPs vs. POPs(Procedural-Oriented Programming)</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Object- Oriented Programming</td><td>Procedural-Oriented Programming</td></tr>
</thead>
<tbody>
<tr>
<td>Bottom-up approach</td><td>Top-down approach</td></tr>
<tr>
<td>Here program is divided into "objects"</td><td>Here program is divided into "functions"</td></tr>
<tr>
<td>It supports code-reusability</td><td>It doesn't support code-reusability</td></tr>
<tr>
<td>It supports Inheritance</td><td>No support for Inheritance</td></tr>
<tr>
<td>It supports access specifiers</td><td>No support for access-specifiers</td></tr>
</tbody>
</table>
</div><p>Now, let's have a look at the 2 important features of OOPs, Class and Object.</p>
<h3 id="heading-class">CLASS</h3>
<p>So, what's a class in Java?</p>
<p>In simple words, it's a template or a blueprint for creating "objects". So we can say a class decides the structure and behavior of the object, a class will have.</p>
<p><strong>Example: Car Class</strong></p>
<p><em>Imagine you are designing a computer program to manage information about cars. In Java, you would create a "Car" class. Here's how you can relate it to real life:</em></p>
<ol>
<li><p><strong>Class:</strong> Car</p>
<ul>
<li>A class named "Car" represents the blueprint for all cars.</li>
</ul>
</li>
<li><p><strong>Attributes (Data):</strong></p>
<ul>
<li><p>In our "Car" class, you can define attributes such as:</p>
<ul>
<li><p>Make (e.g., Audi, BMW)</p>
</li>
<li><p>Model (e.g., Q8, 7series)</p>
</li>
<li><p>Year (e.g., 2022, 2023)</p>
</li>
<li><p>Colour (e.g., Black, Blue)</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><strong>Methods (Behavior):</strong></p>
<ul>
<li><p>You can also define methods to perform actions, such as:</p>
<ul>
<li><p>Start the engine</p>
</li>
<li><p>Stop the engine</p>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<p><em>Now, when you create objects from the "Car" class, each object will have its specific values for the attributes (e.g., one car might be a black Audi from 2022, another may be an Ambassador from 1977), and you can use methods to perform actions on those individual cars (e.g., start the engine of a particular car).</em></p>
<p>So, in this real-life example, the "Car" class serves as a blueprint that defines the structure (attributes) and behaviour (methods) of cars, just like how car manufacturers have blueprints for designing and producing different car models.</p>
<p><strong>NB</strong>: But when we speak in technical terms, <strong>Class in Java is a user-defined datatype</strong> that encapsulates data and behaviour related to a specific concept or entity.</p>
<p>Now let's have a look at Objects in Java.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Define the Car class</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> </span>{
    <span class="hljs-comment">// Attributes</span>
    String make;
    <span class="hljs-keyword">int</span> year;

    <span class="hljs-comment">// Constructor method</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Car</span><span class="hljs-params">(String make, <span class="hljs-keyword">int</span> year)</span> </span>{
        <span class="hljs-keyword">this</span>.make = make;
        <span class="hljs-keyword">this</span>.year = year;
    }

    <span class="hljs-comment">// Methods</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">startEngine</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Engine Started"</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">stopEngine</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Engine Stopped"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CarExample</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create instances (objects) of the Car class</span>
        Car car1 = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"Audi"</span>, <span class="hljs-number">2022</span>);
        Car car2 = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"Ambassador"</span>, <span class="hljs-number">1977</span>);

        <span class="hljs-comment">// Use the methods of the Car class</span>
        car1.startEngine();
        car2.accelerate();
    }
}
</code></pre>
<h3 id="heading-object">OBJECT</h3>
<p>In Java, an object is an instance of a Java class, meaning it is a copy of a specific class.</p>
<p>It has 3 primary characteristics: identity, state, and behaviour.</p>
<p><strong>Identity</strong>: It is a unique identifier like a memory address or a unique name.</p>
<p><strong>State</strong>: It controls aspects of an object; in the case of describing a fan, you could have on, off, low, medium, or high state options.</p>
<p><strong>Behaviour</strong>: It is used to describe what an object can do, such as a fan turning on or off or changing speeds.</p>
<pre><code class="lang-java">Class Cars{
Cars c1 = <span class="hljs-keyword">new</span> Cars() <span class="hljs-comment">// an object is created</span>
} 
<span class="hljs-comment">// Cars - class name</span>
<span class="hljs-comment">// c1 is the object reference variable</span>
<span class="hljs-comment">// new keryword(Dynamic Memory Allocator) -  It allocates memory for the object and initializes it.</span>
<span class="hljs-comment">// Cars() - Constructor call, these are special methods within a class that are used to initialize objects.</span>
</code></pre>
<p>So if "Cars" is the class, then "Audi Q8", "Ferrari 296 GTS", "Honda Jazz" etc. will be the objects. So in short the class just instructs how the object should be.</p>
<p>So now let's have a look at the difference between Classes and Objects in Java.</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Class</td><td>Object</td></tr>
</thead>
<tbody>
<tr>
<td>Class is a logical entity</td><td>Object is a physical entity</td></tr>
<tr>
<td>When a class is created, no memory is allocated.</td><td>But objects are allocated memory space whenever they are created.</td></tr>
<tr>
<td>Class has to be declared first and only once.</td><td>Objects can be created many times as per requirement.</td></tr>
</tbody>
</table>
</div><p>So thats all about the OOPs, Class and Object. Now in the next part, we can look deep into the four main pillars of OOPs, i.e. Inheritance, Polymorphism, Abstraction and Encapsulation.</p>
]]></content:encoded></item></channel></rss>