🚀 Java Series – Day 12 📌 Polymorphism in Java (Method Overloading vs Method Overriding) 🔹 What is it? Polymorphism is one of the four pillars of Object-Oriented Programming (OOP). The word polymorphism means “many forms.” In Java, polymorphism allows the same method name to perform different behaviors depending on the context. There are two main types: • Method Overloading – Same method name with different parameters in the same class. • Method Overriding – A child class provides a specific implementation of a method already defined in the parent class. 🔹 Why do we use it? Polymorphism improves flexibility and code reusability. For example: In a payment system, a method called "pay()" could work differently for CreditCard, UPI, or NetBanking, even though the method name is the same. 🔹 Example: class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { // Method Overriding void sound() { System.out.println("Dog barks"); } } public class Main { // Method Overloading static int add(int a, int b) { return a + b; } static int add(int a, int b, int c) { return a + b + c; } public static void main(String[] args) { Animal a = new Dog(); a.sound(); System.out.println(add(5, 10)); System.out.println(add(5, 10, 15)); } } 💡 Key Takeaway: Polymorphism allows the same method name to behave differently, improving flexibility and making Java programs more powerful. What do you think about this? 👇 #Java #OOP #Polymorphism #JavaDeveloper #Programming #BackendDevelopment
Java Polymorphism Explained: Method Overloading vs Overriding
More Relevant Posts
-
🚀 Java Series – Day 14 📌 Abstract Class vs Interface in Java 🔹 What is it? Both Abstract Classes and Interfaces are used to achieve abstraction in Java, but they are used in different scenarios. An Abstract Class can have: • Abstract methods (without body) • Concrete methods (with implementation) • Instance variables and constructors An Interface mainly contains: • Abstract methods (by default) • Constants (public static final) • Supports multiple inheritance 🔹 Why do we use it? We choose between them based on the requirement: • Use Abstract Class when classes share common code and state • Use Interface when we want to define a contract that multiple classes can implement For example: In a payment system, an abstract class can provide common logic like logging, while an interface defines methods like "pay()" for different payment types. 🔹 Example: abstract class Animal { void eat() { System.out.println("Animal eats food"); } abstract void sound(); } interface Pet { void play(); } class Dog extends Animal implements Pet { void sound() { System.out.println("Dog barks"); } public void play() { System.out.println("Dog plays"); } } public class Main { public static void main(String[] args) { Dog d = new Dog(); d.eat(); d.sound(); d.play(); } } 💡 Key Takeaway: Use abstract classes for shared behavior and interfaces for defining contracts and achieving multiple inheritance. What do you think about this? 👇 #Java #OOP #Abstraction #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
Key Concepts I Learned in Core Java – Method Overriding & Important Keywords As part of my Core Java learning, I explored some important rules related to Method Overriding, Covariant Return Types, Method Overloading, and Java keywords like "final" and "super". Here are the key takeaways: 🔹 Access Modifier Rule In method overriding, the child class method can keep the same access modifier or increase the visibility, but it cannot decrease it. 🔹 Return Type Rule When overriding a method, the return type should be the same. For primitive data types (int, float, double, etc.), the return type cannot be changed. 🔹 Covariant Return Type Java allows the child class method to return a subclass object of the parent method’s return type, provided there is a parent–child relationship between the classes. 🔹 Method Parameter Rule While overriding a method: * Type of parameters must be the same * Number of parameters must be the same * Order of parameters must be the same 🔹 Method Overloading If the method name is the same but parameters are different, it is called Method Overloading, not overriding. 🔹 "final" Keyword in Java "final" can be applied to: * Variables – value cannot be changed * Methods – cannot be overridden * Classes – cannot be inherited 🔹 "super" Keyword The "super" keyword is used to access parent class methods, variables, and constructors from the child class. 🔹 Difference Between "final", "finally", and "finalize" * final → used for variables, methods, classes * finally → block used in exception handling * finalize() → method used in garbage collection Understanding these concepts helped me strengthen my knowledge of OOP principles in Java and how inheritance and method behavior work in real applications. #Java #CoreJava #OOP #MethodOverriding #Programming #JavaDeveloper #LearningJourney
To view or add a comment, sign in
-
-
💎 Understanding the Diamond Problem in Java (and how Java solves it!) Ever heard of the Diamond Problem in Object-Oriented Programming? 🤔 It happens in multiple inheritance when a class inherits from two classes that both have the same method. The Problem Structure: Class A → has a method show() Class B extends A Class C extends A Class D extends B and C Now the confusion is: Which show() method should Class D inherit? This creates ambiguity — famously called the Diamond Problem Why Java avoids it? Java does NOT support multiple inheritance with classes. So this problem is avoided at the root itself. But what about Interfaces? Java allows multiple inheritance using interfaces, but resolves ambiguity smartly. If two interfaces have the same default method, the implementing class must override it. Example: interface A { default void show() { System.out.println("A"); } } interface B { default void show() { System.out.println("B"); } } class C implements A, B { public void show() { A.super.show(); // or B.super.show(); } } Key Takeaways: No multiple inheritance with classes in Java Multiple inheritance allowed via interfaces Ambiguity is resolved using method overriding Real Insight: Java doesn’t just avoid problems — it enforces clarity. #Java #OOP #Programming #SoftwareDevelopment #CodingInterview #TechConcepts
To view or add a comment, sign in
-
Two Pointer Technique: Today I explored the Two Pointer approach in Java, and it completely changed how I look at array problems 👇 🔹 Instead of using nested loops (O(n²)), we can solve many problems in O(n) using two pointers. 💡 Basic Idea: - Use two pointers (left & right) - Move them based on conditions - Reduce unnecessary iterations 📌 Example: Move Zeroes - Keep a slow pointer for non-zero elements - Traverse with a fast pointer - Swap when needed This simple technique makes code more efficient and clean 🔥 Still learning, but improving step by step 💪 👉 What other problems can be solved using two pointers? Today I practiced the Two Pointer approach in Java using the "Move Zeroes" problem 👇 💡 Idea: - Use a slow pointer to track position of non-zero elements - Use a fast pointer to traverse the array - Swap when needed 🧠 Java Code: public class MoveZeroes { public static void moveZeroes(int[] arr) { int slow = 0; for (int fast = 0; fast < arr.length; fast++) { if (arr[fast] != 0) { int temp = arr[slow]; arr[slow] = arr[fast]; arr[fast] = temp; slow++; } } } public static void main(String[] args) { int[] arr = {1, 2, 0, 4, 3, 0, 5, 0}; moveZeroes(arr); for (int num : arr) { System.out.print(num + " "); } } } ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) Small step, but feels great to understand optimization like this 🔥 👉 Any better approaches or suggestions? #Java #DSA #TwoPointers #LearningInPublic #CodingJourney
To view or add a comment, sign in
-
Q. Can an Interface Extend a Class in Java? This is a common confusion among developers and even I revisited this concept deeply today. - The answer is NO, an interface cannot extend a class. - It can only extend another interface. But there is something interesting: - Even though an interface doesn’t extend Object, all public methods of the Object class are implicitly available inside every interface. Methods like: • toString() • hashCode() • equals() These are treated as abstractly redeclared in every interface. ⚡ Why does Java do this? - To support upcasting and polymorphism, ensuring that any object referenced via an interface can still access these fundamental methods. ❗ Important Rule: While you can declare these methods in an interface, you cannot provide default implementations for them. interface Alpha { default String toString() { // ❌ Compile time error return "Hello"; } } Reason? Because these methods already have implementations in the Object class. Since every class implicitly extends Object, allowing default implementations of these methods in interfaces would create ambiguity during method resolution. Therefore, Java does not allow interfaces to provide default implementations for Object methods. 📌 Interfaces don’t extend Object, but its public methods are implicitly available. However, default implementations for them are not allowed. #Java #OOP #InterviewPreparation #Programming #Developers #Learning #SoftwareEngineering
To view or add a comment, sign in
-
🔍 Understanding Arrays in Java (Memory & Indexing) Today I learned an important concept about arrays in Java: Given an array: int[] arr = {10, 20, 30, 40, 50}; We often think about how elements are stored in memory. In Java: ✔ Arrays are stored in memory (heap) ✔ Each element is accessed using an index ✔ JVM handles all memory internally So when we write: arr[0] → 10 arr[1] → 20 arr[2] → 30 arr[3] → 40 arr[4] → 50 👉 We are NOT accessing memory directly 👉 We are using index-based access Very-Important Point: 👉 Concept (Behind the scenes) we access elements using something like base + (bytes × index) in Java 💡 Let’s take an example: int[] arr = {10, 20, 30, 40, 50}; When we write: arr[2] 👉 We directly get 30 But what actually happens internally? 🤔 Behind the scenes (Conceptual): Address of arr[i] = base + (i × size) let's suppose base is 100 and we know about int takes 4 bytes in memory for every element :100,104,108,112,116 So internally: arr[2] → base + (2 × 4) Now base is : 100+8=108 now in 108 we get the our value : 30 Remember guys this is all happening behind the scenes 👉 You DON’T calculate it 👉 JVM DOES it for you 👉 But You Still need to know ✔ Instead, it provides safety and abstraction 🔥 Key Takeaway: “In Java, arrays are accessed using indexes, and memory management is handled by the JVM.” This concept is very useful for: ✅ Beginners in Java ✅ Understanding how arrays work internally ✅ Building strong programming fundamentals #Java #Programming #DSA #Coding #Learning #BackendDevelopment
To view or add a comment, sign in
-
💡 Java Concept: Exception Handling in Method Overriding 🚀 While learning Java, I discovered an important rule that many beginners miss 👇 👉 How exceptions behave when a child class overrides a parent method 🔹 Simple Definition When a subclass overrides a method, it cannot throw broader or new checked exceptions than the superclass. 🧠 Golden Rule 👉 Child class can: ✔ Throw same exception ✔ Throw smaller (child) exception ✔ Throw unchecked exception ✔ Throw no exception 👉 Child class cannot: ❌ Throw new checked exception (not in parent) 🔴 Example (Wrong ❌) class Parent { void show() { } } class Child extends Parent { void show() throws IOException { // ❌ Compile Error System.out.println("Child"); } } 👉 Reason: Parent didn’t declare any exception 🟢 Example (Correct ✅) class Parent { void show() throws Exception { System.out.println("Parent"); } } class Child extends Parent { void show() throws ArithmeticException { System.out.println("Child"); } } 👉 Allowed because: ✔ ArithmeticException is unchecked ✔ OR smaller than parent exception 💡 Why this rule exists? To maintain runtime safety and avoid unexpected errors Parent p = new Child(); p.show(); 👉 Compiler only knows Parent → so child cannot introduce new checked exceptions 🔥 Easy Trick to Remember 👉 "Child can reduce risk, but not increase it" 📌 Small concept, but very important for interviews & real-world coding! #Java #OOP #ExceptionHandling #Programming #Developers #Coding #SoftwareEngineering #LearningJourney
To view or add a comment, sign in
-
-
📘 Why Does Java Allow the `$` Symbol in Identifiers? While learning about Java identifiers, I noticed something interesting. Unlike many programming languages, **Java allows the `$` symbol in identifier names.** Example: ```java int $value = 100; int total$amount = 500; ``` But this raises an interesting question: 👉 Why was `$` added to Java identifiers in the first place? 🔹 The historical reason When Java was designed in the 1990s, the language architects included `$` mainly for internal use by Java compilers and tools. The Java compiler often generates special class names automatically. For example, when you create an inner class, the compiled class file often uses `$` in its name: ``` OuterClass$InnerClass.class ``` Here, `$` helps represent the relationship between the outer class and the inner class. 🔹 Use in frameworks and generated code Many frameworks, libraries, and code generation tools also use `$` internally to create unique identifiers without conflicting with normal developer-defined names. 🔹 Should developers use `$` in identifiers? Technically, it is allowed. However, Java naming conventions discourage its use in normal code. The `$` symbol is generally reserved for: • Compiler-generated classes • Framework-generated code • Internal tooling 🔹 Key takeaway Sometimes language features exist not for everyday developers, but to support the ecosystem of compilers, frameworks, and tools that power the language. The `$` symbol in Java identifiers is one such design choice. #Java #Programming #SoftwareDevelopment #Coding #ComputerScience #LearnInPublic
To view or add a comment, sign in
-
-
Day 11/100 – Java Practice Challenge 🚀 Continuing my #100DaysOfCode journey with another important Java concept. 🔹 Topic Covered: Compile-time vs Runtime Polymorphism 💻 Practice Code: 🔸 Compile-time Polymorphism (Method Overloading) class Calculator { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } } 🔸 Runtime Polymorphism (Method Overriding) class Animal { void sound() { System.out.println("Animal sound"); } } class Cat extends Animal { @Override void sound() { System.out.println("Cat meows"); } } public class Main { public static void main(String[] args) { // Compile-time Calculator c = new Calculator(); System.out.println(c.add(10, 20)); System.out.println(c.add(10, 20, 30)); // Runtime Animal a = new Cat(); a.sound(); } } 📌 Key Learnings: ✔️ Compile-time → method decided at compile time ✔️ Runtime → method decided at runtime ✔️ Overloading vs Overriding difference 🎯 Focus: Understanding how Java resolves method calls 🔥 Interview Insight: Difference between compile-time and runtime polymorphism is one of the most frequently asked Java interview questions. #Java #100DaysOfCode #MethodOverloading #MethodOverriding #Polymorphism #JavaDeveloper #Programming #LearningInPublic
To view or add a comment, sign in
-
The Diamond Problem in Java occurs in languages that allow multiple inheritance, where a class inherits from two classes that share a common superclass. This situation leads to ambiguity when both parent classes define the same method, raising the question of which method should be used. Java circumvents this issue by not supporting multiple inheritance with classes. However, a similar problem can arise with interfaces and default methods. Consider the following example: interface A { default void show() { System.out.println("A"); } } interface B { default void show() { System.out.println("B"); } } class Test implements A, B { public static void main(String[] args) { Test t = new Test(); t.show(); // This results in a compilation error } } In this case, since both interfaces provide the same method, Java requires the class to override it explicitly. Here’s how to resolve it with specific interface calls: class Test implements A, B { public void show() { A.super.show(); // Calls method from interface A B.super.show(); // Calls method from interface B } } This approach allows for explicit selection or combination of behavior from both interfaces. #Java #OOP #InterviewQuestions #BackendDevelopment #Programming
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
https://github.com/raushansingh7033/core-java