<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chinedu Obianonwo on Medium]]></title>
        <description><![CDATA[Stories by Chinedu Obianonwo on Medium]]></description>
        <link>https://medium.com/@christianchinedu19?source=rss-ecc9095ce462------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_vykGpOxrVRTF8njeJpDCw.jpeg</url>
            <title>Stories by Chinedu Obianonwo on Medium</title>
            <link>https://medium.com/@christianchinedu19?source=rss-ecc9095ce462------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 15:20:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christianchinedu19/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Let AI Do the Boring Parts of My Job (So I Could Actually Think)]]></title>
            <link>https://medium.com/@christianchinedu19/how-i-let-ai-do-the-boring-parts-of-my-job-so-i-could-actually-think-6035d7295f1d?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/6035d7295f1d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 07:44:08 GMT</pubDate>
            <atom:updated>2026-10-14T07:44:08.335Z</atom:updated>
            <content:encoded><![CDATA[<p>If you told someone a few years ago that you could type a simple sentence like, <em>“Build a system to track our customer data and check for errors,”</em> and an artificial intelligence would instantly write the code, test it, and fix its own mistakes, they would have thought you were watching a sci-fi movie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFvWPYxMhosoQ0hUq3jlfw.jpeg" /><figcaption>From 2:00 AM debugging marathons to orchestrating autonomous pipelines. How agentic workflows changed the game.</figcaption></figure><p>Today? That’s just a normal Tuesday afternoon.</p><p>When people talk about AI in the tech world, they usually fixate on basic writing tools or simple code completers that finish your sentences like a glorified text-message autocorrect. But there is a universe of difference between a tool that suggests a single word and an <strong>AI agent</strong> an intelligent assistant that can take a massive objective, break it down step-by-step, run its own tests, and patch its own errors while you grab a fresh cup of coffee.</p><p>Here is how I completely overhauled my workflow to let AI handle the repetitive grind, the guardrails that kept me safe, and how you can do it too.</p><h3>Phase 1: Moving From “Typewriters” to Autonomous Helpers</h3><p>Think of a traditional computer utility like a digital typewriter: it sits completely still until you force a key down. An AI agent, on the other hand, acts more like a smart, proactive intern.</p><p>Instead of typing out every single line of code or setting up a project file-by-file from scratch, I stopped focusing purely on the <em>typing</em> and started focusing entirely on the <em>direction</em>.</p><p>My modern workflow looks less like manual labor and more like a feedback loop:</p><ul><li><strong>The Goal:</strong> I hand the AI a crystal-clear objective <em>(e.g., “Take our new sales data, clean up the formatting, and set up a basic safety net to make sure nothing is broken”).</em></li><li><strong>The Check:</strong> The AI scans our current setup to map out the rules and context.</li><li><strong>The Work:</strong> It autonomously writes the necessary files and backend code.</li><li><strong>The Self-Correction:</strong> It runs local tests, catches its own typos or syntax slip-ups, fixes them on the fly, and hands me a pristine final product to review.</li></ul><h3>Phase 2: Four Ways I Put AI to Work</h3><p>Instead of trying to automate my entire existence overnight, I targeted four specific, soul-crushing chores that used to drain my energy:</p><h4>1. Fixing Sudden Changes Automatically</h4><ul><li><strong>The Problem:</strong> Whenever an outside partner or app changes how they send us data, our system snaps, forcing someone to manually rewrite the code.</li><li><strong>The AI Fix:</strong> I set up an alert bridge. When a data structure mutates unexpectedly, an AI agent jumps in, analyzes what changed, writes a patch, and updates our system guidelines instantly.</li></ul><h4>2. Self-Healing Systems (Saving Midnight Emergencies)</h4><ul><li><strong>The Problem:</strong> Pipelines and background systems occasionally crash at 2:00 AM because of a minor timeout or a micro-glitch.</li><li><strong>The AI Fix:</strong> When an error pops up, an automated assistant reads the stack trace, figures out if it’s a passing hiccup or a structural bug, and safely retries or drafts a quick repair branch.</li></ul><h4>3. Writing Safety Checks in Seconds</h4><ul><li><strong>The Problem:</strong> Writing thorough safety, null-value, and quality checks for hundreds of data columns is so deeply tedious that people usually skip it entirely.</li><li><strong>The AI Fix:</strong> I let an AI scan new data sheets, flag messy numbers or missing values, and automatically write all the safety validation checks in seconds.</li></ul><h4>4. Answering Teammate Questions So I Don’t Have To</h4><ul><li><strong>The Problem:</strong> Teammates are constantly pinging Slack asking, <em>“Where does this number come from?”</em> or <em>“Can someone explain this metric?”</em></li><li><strong>The AI Fix:</strong> I connected an AI assistant to our company directory and metadata. Now, when people have questions about our data flows, they can query the AI directly — freeing me up to focus on big-picture architecture.</li></ul><h3>Phase 3: The Hard Lessons (Guardrails You Desperately Need)</h3><p>If you give an AI total, unsupervised freedom over your critical work, <strong>it will eventually break something.</strong> Here are the strict boundaries I had to enforce:</p><blockquote><strong><em>Rule 1: Never Let AI Touch Live Production Data Alone.</em></strong><em> AI is brilliant at drafting, testing, and brainstorming. But it should </em>never<em> have unsupervised power to delete or alter live company records. Always keep a human in the loop before deploying.</em></blockquote><blockquote><strong><em>Rule 2: Context is Everything.</em></strong><em> An AI is only as smart as the information you feed it. If your workspace notes and instructions are a chaotic mess, the AI will get confused and hallucinate answers. Keep your documentation clean.</em></blockquote><blockquote><strong><em>Rule 3: Keep a Paper Trail.</em></strong><em> Always log what the AI did — what files it looked at, what reasoning it used, and what changes it proposed. Accountability matters.</em></blockquote><h3>The Bottom Line</h3><p>AI didn’t take my job; it ruthlessly eliminated the repetitive, mind-numbing chores that used to chain me to my desk. By letting AI handle the initial setup, structural testing, and troubleshooting, I finally got my time back to focus on actual strategy, high-level creativity, and real problem-solving.</p><p>You don’t need to be a hardcore computer scientist to start using these concepts. Pick one small, annoying task this week, hand it to an AI assistant, and see how much mental space you get back.</p><p><em>Have you started experimenting with AI assistants in your daily routine yet? What boring task would you love to hand off first? Let’s talk about it in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6035d7295f1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Death of the Traditional Data Engineer: What to Learn in 2027]]></title>
            <link>https://medium.com/@christianchinedu19/the-death-of-the-traditional-data-engineer-what-to-learn-in-2027-5c3e84148000?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c3e84148000</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[career-advice]]></category>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 14:22:59 GMT</pubDate>
            <atom:updated>2026-10-13T14:22:59.181Z</atom:updated>
            <content:encoded><![CDATA[<p>If you search LinkedIn or Medium for data engineering trends, you will see a paradox. On one hand, the global data engineering market has blown past $105 billion. On the other hand, traditional junior-to-mid-level data engineering roles feel harder to land than ever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ausw6e5eodMT-zlGjBkAnA.jpeg" /><figcaption>An artistic visualization showing messy, tangled orange glowing lines on the left merging and smoothing out into a clean, sleek, glowing blue data grid and modern architecture on the right. It symbolizes the AI/automation cleanup from a chaotic past to a structured future.</figcaption></figure><p>Why? Because <strong>AI didn’t kill data engineering; it automated the boilerplate.</strong></p><p>The era of the “Traditional Data Engineer” someone whose entire job description is writing basic SQL extraction scripts, manually wiring Airflow DAGs, and dragging data from Source A to Warehouse B is coming to a close. AI agents and modern metadata-driven platforms now generate that code in seconds.</p><p>If you want to stay relevant, command top-tier salaries, and thrive in 2026, you need to pivot from being a <em>pipeline mechanic</em> to a <em>data platform architect</em>. Here is what is dying, and more importantly, what you need to learn right now.</p><h3>Part 1: What is Actually Dying?</h3><ul><li><strong>Manual ETL Scripting:</strong> Writing repetitive Python scripts just to move JSON payloads from an API to an S3 bucket. (Generative AI writes this effortlessly now).</li><li><strong>The “Tool-First” Mentality:</strong> Bragging about knowing 15 different tools without understanding how distributed storage or memory management actually functions underneath.</li><li><strong>Set-and-Forget Pipelines:</strong> Building data flows with zero observability, waiting for a panicked executive to text you on a Monday morning because a dashboard broke.</li></ul><h3>Part 2: The 2026 Modern Data Stack &amp; Skills to Master</h3><p>To survive the shift, your learning roadmap needs to move beyond basic SQL and Python into systems that AI cannot easily replicate: architectural judgment, cost optimization, and real-time streaming.</p><h4>1. Real-Time Streaming &amp; Event-Driven Architecture</h4><p>Batch processing is no longer enough. Modern AI applications, LLMs, and real-time analytics need up-to-the-minute data context.</p><ul><li><strong>What to learn:</strong> Master event-driven patterns using <strong>Kafka</strong> or <strong>Flink</strong>. Understand how to handle late-arriving data, watermarking, and stateful stream processing.</li></ul><h4>2. Open Table Formats &amp; Multi-Cloud Interoperability</h4><p>Vendor lock-in is officially out. Companies are moving away from proprietary storage boxes to open, flexible architectures.</p><ul><li><strong>What to learn:</strong> Dive deep into open formats like <strong>Apache Iceberg</strong>, <strong>Delta Lake</strong>, and <strong>Apache Hudi</strong> that bring ACID transactions straight to cloud object storage.</li></ul><h4>3. FinOps &amp; Cloud Cost Optimization</h4><p>When compute was cheap, pipelines were allowed to scan petabytes of data inefficiently. Today, bloated cloud bills are an existential threat to startups.</p><blockquote><strong>What to learn:</strong> Learn how to optimize query execution plans, design smart partition and clustering strategies in Snowflake or BigQuery, and manage cloud costs proactively.</blockquote><blockquote>“<strong>Engineers who save companies money are never laid off.</strong>”</blockquote><h4>4. Data Reliability Engineering &amp; Semantic Governance</h4><p>Data quality is no longer an afterthought; it’s a business risk. With AI consuming data directly, a dirty table doesn’t just skew a chart; it hallucinates a business decision.</p><ul><li><strong>What to learn:</strong> Get comfortable with data observability tools (like Monte Carlo or Great Expectations) and implement <strong>data contracts</strong> between software engineers and data consumers. Master the <strong>dbt Semantic Layer</strong> so metrics remain consistent across every tool.</li></ul><h3>The Bottom Line</h3><p>The market doesn’t need fewer data professionals; it needs <em>smarter</em> ones. AI can write syntax, but it cannot architect a fault-tolerant system, negotiate data governance with stakeholders, or figure out why a distributed cluster is throwing memory errors at 3 AM.</p><p>Stop optimizing for syntax. Start optimizing for <strong>system design and business impact</strong>.</p><p><em>What has been your experience with the job market or modern tooling this year? Are you noticing a shift toward platform engineering in your company? Let’s discuss in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c3e84148000" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Analytics Helps Track Leakages in Business — and Build Smart Controls to Mitigate Risk]]></title>
            <link>https://medium.com/@christianchinedu19/ctively-interacting-with-one-of-the-visual-panels-suggesting-efforts-to-track-leakage-and-1a53d2ee7f2b?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a53d2ee7f2b</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[revenue-loss]]></category>
            <category><![CDATA[revenue-cycle-management]]></category>
            <category><![CDATA[fraud]]></category>
            <category><![CDATA[leakage-solution]]></category>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Sun, 20 Apr 2025 16:38:22 GMT</pubDate>
            <atom:updated>2025-04-20T16:53:06.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Analytics Helps Track Leakages in Business — and Build Smart Controls to Mitigate Risk</h3><p>Every business, no matter how streamlined, is vulnerable to leakage.</p><p>In today’s hyper-competitive landscape, businesses can’t afford to leave money on the table. Yet, many do — without even knowing it.</p><figure><img alt="A Nigerian analyst seated at a modern workspace. Multiple data visualizations, graphs, and dashboards are displayed on transparent digital screens around the subject. The analyst is focused, actively interacting with one of the visual panels — suggesting efforts to track leakage and implement controls. The background shows a clean, high-tech office with analytical themes, projecting a mood of precision, strategy, and problem-solving." src="https://cdn-images-1.medium.com/max/1024/1*Sa8OShOnZHaZbCwp_oQKFA.png" /><figcaption>A Nigerian analyst leverages data analytics to identify business leakages and implement smart controls for risk mitigation.”</figcaption></figure><p>Revenue leakage is the silent killer of profitability. It doesn’t always make headlines, but its impact is real: unbilled services, incorrect provisioning, process inefficiencies, missed upsells, fraud, and data mismatches — all contributing to unaccounted losses.</p><p>Thankfully, analytics is changing that.</p><p>In this post, I’ll explore how data analytics can help businesses <strong>track leakages</strong> across their operations and <strong>build smart controls</strong> to mitigate risk and protect margins.</p><p>But the good news? Data analytics can shine a light on the leaks — and help you build strong controls to plug them before they sink the ship.</p><h3>What Exactly Is Revenue or Business Leakage?</h3><p>Leakage refers to any unintentional loss of revenue, value, or resources due to operational inefficiencies, data mismatches, or system errors. This could stem from:</p><p>Common sources of leakage include:</p><ul><li><strong>Billing mismatches</strong> between service usage and invoicing.</li><li><strong>Inventory discrepancies</strong> in logistics and supply chains.</li><li><strong>Unreconciled transactions</strong> in finance or payments.</li><li><strong>Provisioning errors</strong> in telecom or digital service sectors.</li><li><strong>Shadow IT</strong> or untracked SaaS subscriptions eating into budgets.</li></ul><h3>The Analytics Advantage: From Gut Feel to Precision</h3><p>Traditional audits and manual reviews can’t keep up with the scale and speed of modern business. That’s where <strong>analytics</strong> steps in.</p><p>Here’s how analytics helps track and reduce leakages:</p><h4>1. Automated Reconciliation</h4><p>Analytics tools can match records across systems — like CRM, billing, usage logs, and financial ledgers — spotting discrepancies automatically. For example, if a customer was provisioned a service but wasn’t billed for it, the system flags it instantly.</p><h4>2. Anomaly Detection</h4><p>By building baselines of normal behavior, data systems can detect anomalies — such as a sudden drop in revenue, unusual spikes in usage, or outlier transactions. These flags enable proactive investigations before leakages grow.</p><h4>3. End-to-End Visibility</h4><p>Dashboards can consolidate multiple process stages — from order to cash — and highlight where leakages are occurring in real time. Think of it as a <strong>control tower</strong> for your business operations.</p><h4>4. Root Cause Analysis</h4><p>Analytics isn’t just about detection; it’s about understanding. By tracing issues down to system logs, failed jobs, or delayed approvals, businesses can take <strong>targeted action</strong> instead of guessing.</p><h3>Building Smart Controls Using Data Insights</h3><p>Once you’ve uncovered leakages, the next step is to plug the gaps. Data analytics makes it possible to build <strong>controls that are intelligent, responsive, and automated</strong>.</p><h4>🔒 Some proven controls include:</h4><ul><li><strong>Real-time alert systems</strong> on abnormal activity or data mismatches</li><li><strong>Threshold-based monitoring</strong> on key KPIs like ARPU, provisioning accuracy, or churn</li><li><strong>Rule engines</strong> that block incomplete or inconsistent transactions</li><li><strong>Audit trails</strong> for process handovers</li><li><strong>Daily/weekly dashboards</strong> for revenue assurance reviews</li></ul><p>By turning insights into action, organizations move from <strong>reactive firefighting</strong> to <strong>proactive governance</strong>.</p><h3>Real-World Impact</h3><p>In my experience working with high-volume data environments — from telecom to fintech — the introduction of analytics-based controls has:</p><p>✅ Reduced unbilled usage by 40%<br>✅ Improved provisioning-billing accuracy<br>✅ Flagged suspicious behaviors before fraud took root<br>✅ Saved millions in previously unnoticed leakages</p><p>The ROI on a strong analytics foundation speaks for itself.</p><h3>Conclusion: Don’t Let Leakage Stay Invisible</h3><p>You can’t control what you can’t see.<br> Analytics gives businesses the <strong>visibility</strong>, <strong>velocity</strong>, and <strong>verifiability</strong> they need to identify and eliminate leakages.</p><p>Whether you’re scaling a startup or leading a mature enterprise, now is the time to embed analytics at the core of your control framework. Your bottom line will thank you.</p><p><strong>Want to see how this works in your industry?</strong><br>Let’s connect and explore how data can help secure your revenue and strengthen your controls.</p><p>Because in today’s world, it’s not just about data-driven decisions — it’s about data-driven <em>defense</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a53d2ee7f2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Anti-Money Laundering (AML) in Nigeria’s Telecom Industry: A Sleeping Giant Awakens]]></title>
            <link>https://medium.com/@christianchinedu19/%EF%B8%8F-anti-money-laundering-aml-in-nigerias-telecom-industry-a-sleeping-giant-awakens-e44423ec35fc?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/e44423ec35fc</guid>
            <category><![CDATA[telecommunication]]></category>
            <category><![CDATA[fraud]]></category>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Sun, 13 Apr 2025 12:15:31 GMT</pubDate>
            <atom:updated>2025-04-13T12:19:39.738Z</atom:updated>
            <content:encoded><![CDATA[<p>In the heart of Nigeria’s digital revolution lies a sleeping giant — the telecom industry. Once only the vehicle for calls and texts, telecom companies have transformed into full-blown fintech enablers. With mobile money, airtime-to-cash conversions, and data-for-value ecosystems, telcos are now unofficial financial institutions — and that’s where Anti-Money Laundering (AML) comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4wuSJPVzVpfOhcVShpwKg.png" /><figcaption>AML must evolve in the telecom space before it’s too late.</figcaption></figure><h4>💰 Why AML Should Matter to Telecoms</h4><p>Money laundering isn’t just a “banking problem” anymore. As telcos evolve into providers of financial services — such as mobile wallets, airtime lending, international remittances, and more — they become attractive channels for illicit financial flows. Fraudsters have figured out how to exploit mobile ecosystems to:</p><ul><li>Layer stolen funds across wallets</li><li>Use SIMs for mule accounts</li><li>Launder through airtime-to-cash conversions</li><li>Exploit weak KYC procedures for onboarding</li></ul><p>And it’s not hypothetical. The Nigerian Financial Intelligence Unit (NFIU) and the Central Bank of Nigeria (CBN) have flagged suspicious telecom transactions over the years, often tied to SIM registration gaps and poor compliance reporting.</p><h4>🧩 Where the Loopholes Are</h4><ol><li><strong>SIM Registration Fraud</strong>: Fake or multiple SIM registrations can lead to anonymous wallet creation and shadow transactions.</li><li><strong>Agent Network Abuse</strong>: With thousands of agents acting as last-mile financial service points, monitoring becomes difficult. Rogue agents can facilitate smurfing and illegal cash-outs.</li><li><strong>Weak KYC/AML Controls</strong>: Some telecoms still rely on outdated onboarding mechanisms or don’t update customer profiles regularly.</li><li><strong>Lack of Real-Time Monitoring</strong>: Many telcos don’t have advanced AML tools or AI models for detecting suspicious behavior in real time.</li></ol><h4>📶 What Needs to Change</h4><ul><li><strong>Stronger KYC Protocols</strong>: Telcos must align with banking-grade KYC, linking SIMs directly with verifiable NINs and BVNs.</li><li><strong>Automated AML Screening</strong>: Investing in real-time transaction monitoring systems that flag patterns like frequent high-value airtime purchases, wallet churning, and cross-network triangulations.</li><li><strong>Collaboration with Regulators</strong>: The NCC, CBN, and NFIU need to create unified AML compliance standards for telcos, just like banks.</li><li><strong>Agent Vetting and Training</strong>: Ensuring all agents are vetted, trained, and digitally monitored for suspicious transaction behaviors.</li></ul><h4>🧠 Data Is the New Shield</h4><p>With the massive data footprints available — from call detail records (CDRs), location info, wallet transactions, and usage patterns — telcos are actually better equipped than banks in some ways to fight financial crimes. The key is integration: using data analytics, AI, and cross-sector insights to build holistic risk profiles.</p><h4>🌍 Nigeria as a Case Study for Africa</h4><p>As one of the largest telecom markets in Africa, Nigeria has the opportunity to set the standard. If telcos here can crack the AML nut, it could ripple across Ghana, Kenya, South Africa, and beyond.</p><p><strong>Conclusion:</strong> The telecom industry in Nigeria is sitting on a compliance time bomb — or an opportunity. By embedding robust AML frameworks into their operations, telcos can protect millions of users, build trust, and play a significant role in Nigeria’s fight against financial crime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e44423ec35fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple constructors in Java]]></title>
            <link>https://medium.com/@christianchinedu19/multiple-constructors-in-java-27100b572233?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/27100b572233</guid>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 04:08:45 GMT</pubDate>
            <atom:updated>2023-01-27T04:08:45.713Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes we need to initialize all fields of an object when creating it, but there are cases in which it might be appropriate to initialize only one or several fields.</p><p>Fortunately, for this purpose, a class can have several constructors that assign values to the fields in different ways. In this topic, you will learn how to work with multiple constructors and define the way they interact with each other.</p><h4>Constructor overloading</h4><p>You can define as many constructors as you need. Each constructor should have a name that matches the class name but the parameters should be different. The situation when a class contains multiple constructors is known as <strong>constructor overloading</strong>.</p><p>Here is an example:</p><pre>public class Robot {<br>    String name;<br>    String model;<br><br>    public Robot() {<br>        this.name = &quot;Anonymous&quot;;<br>        this.model = &quot;Unknown&quot;;<br>    }<br><br>    public Robot(String name, String model) {<br>        this.name = name;<br>        this.model = model;<br>    }<br>}</pre><p><strong>The class </strong><strong>Robot has two constructors:</strong></p><ul><li>Robot() is a no-argument constructor that initializes fields with default values;</li><li>Robot(String name, String model) takes two parameters and assigns them to the corresponding fields.</li></ul><p>To create an instance of the class Robot we can use either of the two constructors:</p><pre>Robot anonymous = new Robot(); // name is &quot;Anonymous&quot;, model is &quot;Unknown&quot;<br>Robot andrew = new Robot(&quot;Andrew&quot;, &quot;NDR-114&quot;); // name is &quot;Andrew&quot;, model is &quot;NDR-114&quot;</pre><p>Bear in mind that you cannot define two constructors with the same number, types, and order of the parameters!</p><h4>Invoking constructors from other constructors</h4><p>We can also invoke a constructor from another one. It allows you to initialize one part of an object by one constructor and another part by another constructor.</p><p>Calling a constructor inside another one is done using this. For example:</p><pre>this(); // calls a no-argument constructor</pre><p>If you called a constructor that has parameters you can pass some arguments:</p><pre>this(&quot;arg1&quot;, &quot;arg2&quot;); // calls a constructor with two string arguments</pre><p>Remember, the statement for invoking a constructor should be the first statement in the body of a caller constructor.</p><p>Here is an extended example of the Robot class:</p><pre>public class Robot {<br>    String name;<br>    String model;<br>    int lifetime;<br><br>    public Robot() {<br>        this.name = &quot;Anonymous&quot;;<br>        this.model = &quot;Unknown&quot;;<br>    }<br><br>    public Robot(String name, String model) {<br>        this(name, model, 20);<br>    }<br><br>    public Robot(String name, String model, int lifetime) {<br>        this.name = name;<br>        this.model = model;<br>        this.lifetime = lifetime;<br>    }<br>}</pre><p><strong>Now, the class has three constructors:</strong></p><ul><li>Robot() is a no-argument constructor;</li><li>Robot(String name, String model) is a two-argument constructor that invokes another constructor;</li><li>Robot(String name, String model, int lifetime) is a three-argument constructor that fills all fields.</li></ul><p>The second constructor invokes the third one and passes name, model, and lifetime = 20 to it. The third constructor, in its turn, initializes all fields of the created object.</p><p>Let’s add an output to the third constructor and see the result:</p><pre>public Robot(String name, String model, int lifetime) {<br>    this.name = name;<br>    this.model = model;<br>    this.lifetime = lifetime;<br>    System.out.println(&quot;The third constructor is invoked&quot;);<br>}</pre><p>Let’s now create an instance using the two-argument constructor.</p><pre>Robot andrew = new Robot(&quot;Andrew&quot;, &quot;NDR-114&quot;);</pre><p>The program outputs:</p><pre>The third constructor is invoked</pre><h4>Conclusion</h4><p>In this topic, we’ve covered constructor overloading — creating multiple constructors for the class. Constructor overloading allows us to create an object of the class in different ways depending on the circumstances.</p><p>We can also invoke constructors inside other constructors. All in all, Java provides many useful features for writing constructors and defining interactions between them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27100b572233" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inheritance in Java]]></title>
            <link>https://medium.com/@christianchinedu19/inheritance-in-java-a8086992227d?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8086992227d</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[objects-in-java]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 19:47:12 GMT</pubDate>
            <atom:updated>2023-01-26T19:47:12.514Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Inheritance</strong> is a mechanism for deriving a new class from another class (base class). The new class acquires some fields and methods of the base class. Inheritance is one of the main principles of object-oriented programming. It allows developers to build convenient class hierarchies and reuse existing code.</p><h4>Extending classes</h4><p>When it comes to inheritance, there are several terms. A class <strong>derived</strong> from another class is called a <strong>subclass</strong> (it’s also known as a <strong>derived class</strong>, <strong>extended class</strong> or <strong>child class</strong>). The class from which the subclass is derived is called a <strong>superclass</strong> (also a <strong>base class</strong> or a <strong>parent class)</strong>.</p><p>To derive a new class from another, the keyword extends is used. The common syntax is shown below.</p><pre>class SuperClass { }<br>class SubClassA extends SuperClass { }<br>class SubClassB extends SuperClass { }<br>class SubClassC extends SubClassA { }</pre><p><strong>There are important points about inheritance in Java:</strong></p><ul><li>Java doesn’t support multiple-class inheritance, meaning that a class can only inherit from a single superclass;</li><li>a class hierarchy can have multiple levels (class C can extend class B that extends class A);</li><li>a superclass can have more than one subclass.</li></ul><p>A subclass inherits all public and protected fields and methods from the superclass. A subclass can also add new fields and methods. The inherited and added members will be used in the same way.</p><p>A subclass doesn’t inherit private fields and methods from the superclass. However, if the superclass has public or protected methods for accessing its private fields, these members can be used inside subclasses.</p><p>Constructors are not inherited, but the superclass’s constructor can be invoked from the subclass using the special keyword super. This keyword is discussed in more detail in another topic.</p><p>If you’d like the base class members to be accessible from all subclasses but not from the outside code (excluding the same package), use the access modifier protected.</p><p><strong>Inheritance</strong> represents the <strong>IS-A</strong> relationship. A base class represents the general and a subclass represents the particular or specific.</p><p><strong>An example of a class hierarchy</strong></p><p>Let’s consider a more graphic example. A telecommunication company serves clients. It has a small staff consisting only of managers and programmers. Let’s consider a class hierarchy for people associated with the company’s activities (including clients).</p><p>At first, we present the hierarchy as a figure. An arrow indicates that one class extends another one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*72eNeQwFWODzsCXlFnTdDg.png" /><figcaption><strong>class hierarchy in java</strong></figcaption></figure><p><strong>The class hierarchy for the telecommunication company</strong></p><ul><li>the base class Person has fields for storing common data: name, year of birth, and address;</li><li>the class Client has additional fields to store the contract number and status (gold or not);</li><li>the class Employee stores the start date of work for the company and the salary;</li><li>the class Programmer has an array of the programming languages a programmer uses;</li><li>the class Manager may have a dazzling smile.</li></ul><p>Let’s see the code:</p><pre>class Person {<br><br>    protected String name;<br>    protected int yearOfBirth;<br>    protected String address;<br>// public getters and setters for all fields here<br><br>}<br><br>class Client extends Person {<br>    protected String contractNumber;<br>    protected boolean gold;<br>    // public getters and setters for all fields here<br>}<br><br>class Employee extends Person {<br>    protected Date startDate;<br>    protected Long salary;<br>    // public getters and setters for all fields here<br>}<br><br>class Programmer extends Employee {<br>    protected String[] programmingLanguages;<br>    public String[] getProgrammingLanguages() {<br>        return programmingLanguages;<br>    }<br>    public void setProgrammingLanguages(String[] programmingLanguages) {<br>        this.programmingLanguages = programmingLanguages;<br>    }<br>}<br><br>class Manager extends Employee {<br>    protected boolean smile;<br>    public boolean isSmile() {<br>        return smile;<br>    }<br>    public void setSmile(boolean smile) {<br>        this.smile = smile;<br>    }<br>}</pre><p>This hierarchy has two levels and five classes overall. All fields are protected , which means they are visible to subclasses. Each class also has public getters and setters, but some are skipped in the code as these classes use the default no-argument constructor.</p><p>Let’s create an object of the Programmer class and fill the inherited fields using the inherited setters. To read the values of the fields, we can use inherited getters.</p><pre>Programmer p = new Programmer();<br>p.setName(&quot;John Elephant&quot;);<br>p.setYearOfBirth(1985);<br>p.setAddress(&quot;Some street, 15&quot;);<br>p.setStartDate(new Date());<br>p.setSalary(500_000L);<br>p.setProgrammingLanguages(new String[] { &quot;Java&quot;, &quot;Scala&quot;, &quot;Kotlin&quot; });<br>System.out.println(p.getName()); // John Elephant<br>System.out.println(p.getSalary()); // 500000<br>System.out.println(Arrays.toString(p.getProgrammingLanguages())); // [Java, Scala, Kotlin]</pre><p>We also can create an instance of any class included in the considered hierarchy.</p><p>So,<strong> inheritance</strong> provides a powerful mechanism for code reuse and writing convenient hierarchies. Many things in the real world can be simulated, like hierarchies from a more general to a more particular concept.</p><h4>Final classes</h4><p>If a class is declared with the keyword final, it cannot have subclasses at all.</p><pre>final class SuperClass { }</pre><p>If you try to extend the class, a compile-time error will occur.</p><p>Some standard classes are declared as final: Integer, Long, String, Math. They cannot be extended from.</p><h4>Conclusion</h4><p><strong>Inheritance</strong> allows you to build class hierarchies when subclasses (children) take some fields and methods of the superclass (parent). Such a hierarchy can have multiple levels, but every class can inherit only from a single superclass. A good class hierarchy helps to avoid code duplication and makes your program more modular. If a class should not have subclasses, it should be marked as final.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8086992227d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getters and setters in Java]]></title>
            <link>https://medium.com/@christianchinedu19/getters-and-setters-in-java-3300e3ad53c6?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/3300e3ad53c6</guid>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 15:43:06 GMT</pubDate>
            <atom:updated>2023-01-25T15:43:06.808Z</atom:updated>
            <content:encoded><![CDATA[<p>In most cases, a class does not expose its fields to other classes. Instead, it makes its fields accessible through so called accessor methods. In this topic, you will learn what advantages this approach offers and how to use it properly.</p><h4>Data encapsulation</h4><p>According to the <strong>data encapsulation</strong> principle, the fields of a class cannot be directly accessed from other classes. The fields can be accessed only through the methods of that particular class.</p><p>To access hidden fields, programmers write special types of methods: <strong>getters</strong> and <strong>setters</strong>. Getters can only read fields, and setters can only write (modify) the fields. Both types of methods should be public.</p><h4>Using these methods gives us some advantages:</h4><ul><li>the fields of a class can be made read-only, write-only, or both;</li><li>a class can have total control over what values are stored in the fields;</li><li>users of a class don’t know how the class stores its data and don’t depend on the fields.</li></ul><h4>Getters and setters</h4><p>Java doesn’t provide any special keywords for getter and setter methods. Their main difference from other methods is their names.</p><p>According to the <a href="https://docstore.mik.ua/orelly/java-ent/jnut/ch06_02.htm">JavaBeans Convention</a>:</p><ul><li><strong>getters </strong>start with <strong>get</strong>, followed by the variable name, with the first letter of the variable name capitalized;</li><li><strong>setters </strong>start with <strong>set</strong>, followed by the variable name, with the first letter of the variable name capitalized.</li></ul><p>This convention applies to any type except boolean. A <strong>getter</strong> for a boolean field starts with <strong>is</strong>, followed by the variable name.</p><p><strong>Example 1.</strong> The class Account has four fields: id, code, balance and enabled. Each field has a keyword <strong>private</strong> to hide the field from direct access from other classes. Also, the class has <strong>public</strong> getters and setters for accessing fields through these methods.</p><pre>class Account {<br><br>    private long id;<br>    private String code;<br>    private long balance;<br>    private boolean enabled;<br><br>     // getter<br>    public long getId() {<br>        return id;<br>    }<br>    // setter<br>    public void setId(long id) {<br>        this.id = id;<br>    }<br><br>    public String getCode() {<br>        return code;<br>    }<br><br>    public void setCode(String code) {<br>        this.code = code;<br>    }<br><br>    public long getBalance() {<br>        return balance;<br>    }<br><br>    public void setBalance(long balance) {<br>        this.balance = balance;<br>    }<br><br>    public boolean isEnabled() {<br>        return enabled;<br>    }<br><br>    public void setEnabled(boolean enabled) {<br>        this.enabled = enabled;<br>    }<br><br>}</pre><p>Here you can see the different getters and setters for the class Account. Just as the convention states, the boolean field enabled has a different getter name: it starts with the word is instead of get.</p><p>Let’s create an instance of the class and fill the fields, then read values from the fields and output them.</p><pre>Account account = new Account();<br>account.setId(1000);<br>account.setCode(&quot;62968503812&quot;);<br>account.setBalance(100_000_000);<br>account.setEnabled(true);<br>System.out.println(account.getId());      // 1000<br>System.out.println(account.getCode());    // 62968503812<br>System.out.println(account.getBalance()); // 100000000<br>System.out.println(account.isEnabled());  // true</pre><p>Sometimes, <strong>getters </strong>or <strong>setters</strong> can contain a more sophisticated logic. For example, <strong>getters</strong> may return non-stored values (calculated at runtime), or <strong>setters</strong> may also in some cases modify the value of another field according to changes. But usually, getters and setters have a minimum of programming logic.</p><p><strong>Example 2.</strong> In the following class, the setter setName doesn&#39;t change the current value if the passed value is null.</p><pre>class Patient {<br><br>    private String name;<br>    public Patient(String name) {<br>        this.name = name;<br>    }<br>    public String getName() {<br>        return this.name;<br>    }<br>    <br>    public void setName(String name) {<br>        if (name != null) {<br>            this.name = name;<br>        }<br>    }<br>}</pre><h4>Conclusion</h4><p>To restrict access to fields from external code, make them private and write suitable <strong>getters/setters</strong> to <strong>read/change </strong>only the fields you need. Do not forget to make use of the naming convention when writing them.</p><p>Note, modern IDEs (such as <strong>IntelliJ IDEA</strong>) can generate getters and setters automatically based on class fields.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3300e3ad53c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access modifiers in Java]]></title>
            <link>https://medium.com/@christianchinedu19/access-modifiers-in-java-e4479b74d00e?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4479b74d00e</guid>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 15:34:56 GMT</pubDate>
            <atom:updated>2023-01-24T15:34:56.203Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve probably seen the following piece of code:</p><pre>public static void main(String[] args) { <br>    // some code goes here<br>}</pre><p>Why is the word “public” even there? As you could probably guess, it means that the main(...) method is available for everyone. The word public here is an access modifier.</p><p>An<strong> access modifier</strong> is a special keyword that specifies who is allowed to use your code or a special part of it. It can be placed in front of any field, method or the entire class.</p><p>So, you already know at least one of the access modifiers! The others are: package-private, protected, and private. Why do we need them? Let&#39;s find out.</p><p>OK, so why should I use them?</p><p>There are two main reasons to take access under control: clarity and safety of code.</p><p><strong>Code clarity.</strong> Imagine your code is a complicated engine of a washing machine. There are some available functions — for example, choosing a washing program or starting a washing process.</p><p>What can we do to help the user quickly figure out how to wash their clothes? We can cover the engine with the body and add some buttons for choosing a washing mode and starting the process. The user has no need to know what is going on inside the machine’s body; the buttons to get the result are more than enough.</p><p>That’s how access control helps in code — you can <strong>“hide” the engine from the user </strong>by restricting access and simply provide them with the public “buttons”.</p><p><strong>Code safety. </strong>Now imagine you have developed a rather useful library that is used by other developers. One day some Jane Doe wants to use your code’s functionality in her project, but the problem is that she needs to change one variable in one of your classes. If it is public, nothing can stop her from doing that in her code before using method A from the library.</p><p>What can happen if the variable is used somewhere in method B? The B method would probably start to act unpredictably. So, protecting important parts of your code is a guarantee that it will be<strong> used as an unmodifiable part </strong>and its behavior will be the exact one you have developed for it.</p><h4>Public and package-private classes</h4><p>In fact, when you manage the access in your code, you simply divide objects of your program into two main groups: top-level items and low-level items. Fields and methods that are explicitly used outside the class are called top-level fields and methods. If fields and methods are used inside the class, they are known as low-level ones.</p><p>This low-level and top-level logic is also applicable to classes.<br>Usually, using low-level items helps to unload top-level classes, methods or fields in order to structure and decompose the code. If these items are not explicitly used, it will be efficient to restrict access to them.</p><p>Now let’s see how we can set restrictions to different parts of the code. A top-level class (not an inner one, not a nested one) can have one of two following modifiers:</p><ul><li><strong>package-private (default, no explicit modifier): </strong>visible only for classes from the same package;</li><li><strong>public:</strong> visible to all classes everywhere.</li></ul><p>Here is a class inside the package org.hyperskill.java.packages.theory.p1. with default package-private access:</p><pre>package org.hyperskill.java.packages.theory.p1;<br>class PackagePrivateClass{<br>}</pre><p>This class can be used only by other classes from the same package. It’s not even visible for classes from any other package, including:</p><pre>org.hyperskill<br>org.hyperskill.java.packages.theory<br>default package</pre><p>Note the first two examples — if the class is package-private in package a.b, it is still unavailable from package a.c and package a itself.</p><p>Here is a public class inside the package org.hyperskill.java.packages.theory.p2</p><pre>package org.hyperskill.java.packages.theory.p2;<br>public class PublicClass {<br>}</pre><p>This class has no access restrictions, it is visible to all classes and can be used everywhere, including:</p><pre>org.hyperskill<br>org.hyperskill.java.packages.theory<br>org.hyperskill.java.packages.theory.p1<br>default package</pre><p><strong>The common way of using top-level class modifiers is:</strong></p><ol><li>make the classes containing methods for users (the “buttons”) <strong>public</strong>;</li><li>make all other classes with low-level logic methods used by public ones <strong>package-private</strong> (cover the engine with the body).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*DTHRxvlb4L4J9Cw--QLB6Q.png" /></figure><p>Remember: everything that’s not meant to be used/changed by classes from other packages, should not be public.</p><h4>Private members</h4><p>A class member (a field or a method, e.g. class constructor) has more options to choose from: <strong>private</strong>, <strong>package-private</strong>, <strong>protected</strong> and <strong>public</strong>. As you can see, there are two additional modifiers here. Let’s consider member modifiers in more detail.</p><p>Fields are often declared <strong>private </strong>to control access to them from any other class. In some cases, these fields are only used internally in the class and there is no way to change and even access them from any other class. In other cases, it can be done via <strong>accessor methods </strong>(e.g. getters and setters).</p><p><strong>Getter</strong> and <strong>setter</strong> methods are used to protect and hide your data when creating classes. A getter method returns the value of a field, while a setter method sets or updates the value. We will discuss the main features of getter and setter methods later in the topic related to these terms.</p><p>Private methods are used to hide the internal low-level logic implementation from the rest of the code and make public methods more brief and readable.</p><p>Here is the class Counter with the private field current. This field can be read-only with the method getCurrent() , a getter method, and changed with the inc() method. The last one is not exactly a setter method, because it doesn&#39;t manually set a value to a current variable, but just increments it.</p><pre>public class Counter {<br>   private long current = 0;<br>public long getCurrent() {<br>       return current;<br>   }<br><br>   public long inc() {<br>       inc(1L);<br>       return current;<br>   }<br><br>   private void inc(long val) {<br>       current += val;<br>   }<br>}</pre><p>Sometimes, a private class constructor is required. This type of constructor can only be used inside the class, e.g. from another constructor, which can be public or private too, or from the class methods.</p><h4>Package-private members</h4><p>A<strong> package-private</strong> access modifier does not require any keyword. If a field, a method, or a constructor has this modifier, then it can be read or changed from any class inside the same package.</p><p>Let’s see an example. Here are two classes in the same package: Salary and Promotion.</p><p>The class Salary has a package-private field and a constructor. An instance of the Salary class can be created inside a class of Promotion, and the field can also be accessed by Promotion and its members because they belong to the same package.</p><pre>public class Salary {<br>    long income;<br>   Salary(long income) {<br>        this.income = income;<br>    }<br>}<br>public class Promotion {<br>    Salary salary;<br>    Promotion(Salary salary) {<br>        this.salary = salary;<br>    }<br>    public void promote() {<br>        salary.income += 1500;<br>    }<br>}</pre><h4>Protected and public members</h4><p>Disclaimer: you will learn to use these two modifiers later!</p><p>If a class member has the <strong>protected </strong>access modifier, it can be accessed from classes inside the same package and all subclasses of this class (including the ones in other packages). For now, it is important to remember, that the protected option is less restricting than package-private as it allows some classes from other packages access to the code member.</p><p>A<strong> public</strong> access modifier means that there is no restriction on using a field, method, or class. It’s often used for constructors, methods representing the class API but not commonly used with fields.</p><p>Here are common ways to understand which access modifier to choose. It is not the ultimate algorithm, because the inheritance and subclass topics have not been covered yet, but it can help you understand the main use cases of the modifiers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*kh-xNFHpNrz5LAI4ul5QWg.png" /><figcaption>flow chart of access modifiers (from most to least limiting):</figcaption></figure><p>So, let’s review the names of access modifiers (from most to least limiting):</p><ul><li><strong>private</strong> — available only inside a class;</li><li><strong>package-private</strong> (also known as <strong>default</strong>, implicit) — available for all classes in the same package;</li><li><strong>protected</strong> — available for classes in the same package and for subclasses (will be covered later);</li><li><strong>public </strong>— available for all classes everywhere.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*7WxiiwwUtYVihk8HOj_c4A.png" /><figcaption>Table name of access modifiers</figcaption></figure><p>The table above illustrates the level of access provided by the access modifiers: the class always has access to its members and so on. Note that by a subclass here, we mean only a subclass of this class used in another package. We will learn inheritance and subclasses later.</p><p>Remember, that only <strong>public</strong> or default (no keywords) modifiers may be used when declaring classes. All four of them can be applied to class members: fields, methods, etc.</p><h4>Conclusion</h4><p>In this topic, you learned about access modifiers that allow you to determine who will be able to use the code. Using them makes your code safer and clearer. In conclusion, here is a piece of advice: use the most restrictive access level that makes sense for a particular member. Don’t make all members public.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4479b74d00e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Packages in Programming]]></title>
            <link>https://medium.com/@christianchinedu19/packages-in-programming-526b1d72e689?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/526b1d72e689</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 12:41:51 GMT</pubDate>
            <atom:updated>2023-01-24T12:41:51.215Z</atom:updated>
            <content:encoded><![CDATA[<p>Large Java projects have a lot of classes. It’s difficult to manage them if they are stored in the same directory. <strong>Packages</strong> provide a mechanism for grouping classes together in the same module (or package). In this topic, you will learn how to use them to better systemize your classes and keep your app tidy.</p><h4>The basics of packages</h4><p><strong>In general, packages have many advantages. They allow us to:</strong></p><ul><li>group related classes together, which makes it easier to figure out where a certain class is;</li><li>avoid conflicting class names;</li><li>control access to classes and members with access modifiers (you’ll learn about this in another topic).</li></ul><p>According to the naming convention, package names are always lowercase, for example:</p><pre>model<br>collection<br>utils</pre><p>A package can contain other packages, and the whole structure resembles directories in a file system. Here is an example project with a simple tree of packages and classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*voASNpVjwG2o6hg7" /></figure><p>At the top of the tree, there is a directory src. This is the source root directory. In this tree, the full name of the class User is org.company.webapp.data.User.</p><p>You can output the full name using the following code:</p><pre>System.out.println(User.class.getName()); // org.company.webapp.data.User</pre><p>Classes declared inside a package have a special keyword package at the top of the file.</p><pre>package org.company.webapp.data;<br><br>public class User {<br>}</pre><h4>Avoiding conflicting class names</h4><p>When you use external libraries, two classes may have the same name. Packages allow us to avoid a conflict of class names because the full class name includes the name of the package. So even if two classes from different packages have the same name, their full names will be different. That is, of course, if there are no conflicts between the package names.</p><p>To avoid creating packages with the same names as other public packages, it is generally recommended to start your package hierarchy with the reversed domain name of your company (or another organization). For example:</p><pre>org.company<br>org.hyperskill<br>net.labs</pre><p><strong>Importing classes</strong></p><p>If two classes are located in the same package, using one class inside the other is no problem. If this is not the case and the classes are in different packages, you need to write an import statement to use one class inside the other. The import statement is defined by the keyword<strong> </strong>import.</p><p>Here is an example. We have two public classes in different packages:</p><pre>org.hyperskill.java.packages.theory.p1.A<br>org.hyperskill.java.packages.theory.p2.B</pre><p>To use class B inside class A we should use an import statement.</p><pre>package org.hyperskill.java.packages.theory.p1;  // current package<br>import org.hyperskill.java.packages.theory.p2.B; // it&#39;s required to use the import<br><br>public class A {<br>    public static void method() {<br>        B b = new B();<br>    }<br>}</pre><p>The package declaration and import statements are optional. If both of them are present, the package must come before all imports! Otherwise, we get a compilation error.</p><p>It is also possible to import all classes from a package. To do this, we need to write <strong>*</strong> in the import statement instead of a particular class name.</p><pre>import org.hyperskill.java.packages.theory.p3.*; // import all classes from the package</pre><p>Don’t do this too often. In some cases, this is considered a bad practice and can break the compatibility of your program with new versions of Java. <a href="https://stackoverflow.com/questions/147454/why-using-a-wild-card-with-a-java-import-statement-bad">Here is an interesting discussion</a> about such statements.</p><p>If two classes belong to the same package, you don’t need to import them to each other.</p><p>There is a way to use a class from another package without the import statement. In this case, you should write the full class name (including the full package path) instead of the name of the class itself (short name). This is how we would use the Scanner class without explicitly importing it first:</p><pre>java.util.Scanner scanner = new java.util.Scanner(System.in);<br>java.util.Date now = new java.util.Date();</pre><p>Let’s polish the information about access to classes inside the package with the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0-JQcHR7lnQgGSK0" /></figure><p>The classes City and Area are located in the same subpackage state, so you can use one class inside the other with a <strong>short name</strong>. The same thing is true for the classes Urban and Rural in the subpackage territory.</p><p>If you want to use any class of the subpackage territory inside the class of the subpackage state or vice versa, you need to write the <strong>full name</strong> of this class, <strong>import</strong> <strong>the class,</strong> or import the whole subpackage. Moreover, if you want to use classes from the subpackages state or territory inside the class Republic from the package country or vice versa, you also need to write a <strong>full name</strong> or <strong>import</strong> <strong>the class</strong>. This should be done even if these packages are in the same root package (here it is the package country).</p><p><strong>Importing standard classes</strong></p><p><em>There is no difference between importing standard or custom classes.</em></p><p>For example, many Java developers use java.util.Scanner to work with the standard input/output. In their programs, they include the following import:</p><pre>import java.util.Scanner;</pre><p>After this, we can create an instance of the Scanner like in the examples above and use it in our programs.</p><p>Even though we have to import most packages to use their classes, there is a Java package that is always automatically imported, namely, java.lang. This package contains many widely used classes, such as String, System, Long, Integer, NullPointerException and others.</p><h4>Static imports</h4><p>We can also import static members (methods and fields) of a class inside another class. If we write an asterisk <strong>* </strong>in the import statement, we don&#39;t need to write the imported class name before invoking static methods or reading static fields.</p><p>Here is an example of the static import of the class Arrays, which contains a lot of useful methods for processing arrays.</p><pre>package org.hyperskill.java.packages.theory;<br>import static java.util.Arrays.*; // instead of the statement &quot;import java.util.Arrays;&quot;<br>public class Main {<br>    public static void main(String[] args) {<br>        int[] numbers = { 10, 4, 5, 47, 5, 12 }; // an array<br>        sort(numbers); // instead of writing Arrays.sort(...)<br>        int[] copy = copyOf(numbers, numbers.length); // instead of writing Arrays.copyOf(...)<br>    }<br>}</pre><h4>Default package</h4><p>If we do not write a package statement before defining our class, it will be placed inside the <strong>default package</strong>. This package has a big disadvantage — classes located here can’t be imported to classes located inside named packages.</p><p>The following class cannot be used in a class located inside packages since there is no package declaration.</p><pre>// no package declaration<br>public class Person {<br>    String firstName;<br>    String lastName;<br>}</pre><p>Do not use the <strong>default package</strong> for real applications. It is perfectly fine for simple, educational applications, like “Hello world”, but more complex projects will be better in named packages.</p><h4>Conclusion</h4><p>Packages are a very useful tool for OOP projects. They allow us to structure the source code better, and they make it more maintainable. That is very important for big projects that can consist of thousands of classes.</p><p>Packages are also very helpful for avoiding conflicting class names because the full class name includes the path of the whole package. If we are careful with the naming of the package itself, there should be no conflicts!</p><p>Another thing to remember is that packages affect the visibility of classes and class members to each other. That means that we should keep in mind the imports, static members, and the default package.</p><p>Creating packages even for small applications is great training for your great future projects!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=526b1d72e689" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instance methods in Java]]></title>
            <link>https://medium.com/@christianchinedu19/instance-methods-in-java-4cdfa287f6ce?source=rss-ecc9095ce462------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cdfa287f6ce</guid>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Chinedu Obianonwo]]></dc:creator>
            <pubDate>Mon, 23 Jan 2023 23:53:26 GMT</pubDate>
            <atom:updated>2023-01-23T23:53:26.908Z</atom:updated>
            <content:encoded><![CDATA[<p>As you know, a class is one of the fundamental concepts in Java. You develop the logic of a program by creating fields and methods inside classes. Fields describe an object’s properties and methods describe what an object does. In this topic, we will go on to discuss the nature of methods in Java. All methods can be divided into two groups: <strong>instance</strong><em> </em>and<em> </em><strong>static</strong>. We were mostly focused on the static ones previously, so now let’s learn more about instance methods to better understand the differences between the two.</p><h4>What’s the difference?</h4><p>Let’s look at the code below. Here we have a class named Human with two fields and two methods.</p><pre>class Human {<br>    String name;<br>    int age;<br>    public static void printStatic() {<br>        System.out.println(&quot;It&#39;s a static method&quot;);<br>    }<br>    public void printInstance() {<br>        System.out.println(&quot;It&#39;s an instance method&quot;);<br>    }<br>}</pre><p>The modifier public isn&#39;t important for us now. It just means that other classes can also get access to our methods.</p><p>As you see, the methods printStatic and printInstance have differences in declaration. When you see a method, you can easily understand: if there is a word static, then the method is <strong>static</strong>; if there is no word static, then the method is an <strong>instance </strong>one.</p><p>Now let’s see what this really means!</p><h4>Understanding: static and instance</h4><p>To invoke a static method we don’t need to create an object. We just call the method with the class name.</p><pre>public static void main(String[] args) {<br>Human.printStatic(); // will print &quot;It&#39;s a static method&quot;<br>}</pre><p>In other words, you can say that a static method belongs to a class (because we don’t need an object).</p><p>An instance method requires a different invocation. As you already guessed, to invoke an instance method we have to create an object first. Otherwise, there is no way to use an instance method.</p><p>It’s called an instance method because an instance is a concrete representation of an object.</p><p>Here we call the method printInstance for two different objects:</p><pre>public static void main(String[] args) {<br>        <br>    Human peter =  new Human();<br>    peter.printInstance(); // will print &quot;It&#39;s an instance method&quot;<br>    Human alice =  new Human();<br>    alice.printInstance(); // will print &quot;It&#39;s an instance method&quot;<br>}</pre><p>So, we can say that an instance method is a method that belongs to each object that we created of the particular class.</p><h4>Instance methods: features</h4><p>Instance methods have a great advantage: they can access fields of the class.</p><p>To illustrate the feature, let’s modify our class Human. Again, we have one static method averageWorking and one instance method work.</p><pre>class Human {<br>    String name;<br>    int age;<br><br>    public static void averageWorking() {<br>        System.out.println(&quot;An average human works 40 hours per week.&quot;);<br>    }<br>    public void work() {<br>        System.out.println(this.name + &quot; loves working!&quot;);<br>    }<br>    public void workTogetherWith(Human other) {<br>        System.out.println(this.name + &quot; loves working with &quot; + other.name + &#39;!&#39;);<br>    }<br>}</pre><p>The keyword this represents a particular instance of the class.</p><p>It’s easier to understand by an example:</p><pre>public static void main(String[] args) {<br>        <br>    Human.averageWorking(); // &quot;An average human works 40 hours per week.&quot;<br>    Human peter =  new Human();<br>    peter.name = &quot;Peter&quot;;<br>    peter.work(); // &quot;Peter loves working!&quot;<br>        <br>    Human alice =  new Human();<br>    alice.name = &quot;Alice&quot;;<br>    alice.work(); // &quot;Alice loves working!&quot;<br>    peter.workTogetherWith(alice); // &quot;Peter loves working with Alice!&quot;<br>}</pre><p>Look, now we have different outputs for the method work because two different objects have different values for name. First, we created peter and gave him a name, then by invoking peter.work() we actually saw his name in the output. We did the same with alice and also saw her name in the output.</p><p>Look at the workTogetherWith method. The keyword this allows us to access a field of the particular object and distinguish it from the same field of another object.</p><p>This keyword this is optional, so the code will work the same without it. But it&#39;s a good practice to add it to avoid confusion.</p><p>Of course, instance methods can take arguments and return values just as you saw in the previous topics. Return values can be of any type including the same type as the defined class.</p><h4>Summary</h4><p>In Java, every method should be declared within a class. The difference between instance and the static methods lies in whether they interact with an object or not. Let’s recap:</p><ul><li>static method is associated with the class as a whole;</li><li>an instance method can only be invoked through an instance of a class, so that you have to create an object first;</li><li>instance methods can access the fields of the class with this keyword.</li></ul><p>Instance methods allow programmers to manipulate particular objects of a class. And because of it, they give us more functionality and are used more often than static methods!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cdfa287f6ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>