Posts

Inheritance in Java

Image
Imagine a Family : Explaining Inheritance in Java Think of a parent and child. The child inherits some traits from the parent—like eye color, habits, or the ability to speak a certain language. Similarly, in Java, a class can inherit properties and behaviors (methods) from another class. Let’s break it down: Parent Class (Super Class): Think of it as a “general” class. For example, Animal. Child Class (Sub Class): Think of it as a “specific” version of that class. For example, Dog or Cat. If the Animal class has a method called makeSound(), the Dog and Cat classes can use that method too—they inherit it. Simple Example: class Animal {     void makeSound() {         System.out.println("Animal makes sound");     } } class Dog extends Animal {     void bark() {         System.out.println("Dog barks");     } } Now if we do this: Dog myDog = new Dog(); myDog.makeSound(); // Inherited from Animal myDog...

What is Polymorphism?

Image
Polymorphism is a big word that simply means “many forms.” In Java, it means one action can behave differently depending on the object. Real-Life Example : Remote Control Imagine you have one remote control that can: Control a TV Control an AC Control a projector You’re pressing the same button, but it performs different actions based on the device. That’s polymorphism in real life—same action, different behavior. In Java: What does it mean? In Java, polymorphism allows one method or one object to behave in multiple ways. There are two types: 1. Compile-time Polymorphism (Method Overloading) 2. Runtime Polymorphism (Method Overriding) 1. Compile-time Polymorphism (Method Overloading) Same method name, but different parameters. Example : Calculator public class Calculator {     public int add(int a, int b) {         return a + b;     }     public double add(double a, double b) {         return a + b; ...

What is Encapsulation?

Image
Think of encapsulation like a capsule of medicine. A capsule keeps the medicine inside and controls how it is used. In Java, encapsulation means hiding the inner details of an object and only showing what is necessary — just like how a capsule hides the bitter medicine and gives it in a safe way. --- Real-Life Example : ATM Machine Imagine an ATM machine. You insert your card, enter your PIN, and withdraw money. But you don’t know how the ATM internally processes your PIN or how it deducts money from your account. That’s encapsulation! The inner details are hidden. You only use the buttons and see the screen. You can’t access or change the machine's internal parts. In Java: How is Encapsulation Done? Encapsulation in Java is done using: 1. Private variables : These are hidden from outside classes. 2. Public methods (getters and setters) : These provide controlled access to the variables. Code Example: Let’s say we’re creating a Bank Account:   How it works : You cannot...