Day 21 – Can We Override Static Methods in Java? 🤔 This is one of those classic trick questions every Java developer faces at least once — “Can we override static methods?” Let’s clear the confusion once and for all Short Answer: No, we cannot override static methods in Java. But wait — if we write the same static method in the subclass, Java doesn’t throw an error. So what’s happening there? What Actually Happens When a subclass defines a static method with the same name and signature as the one in the parent class — It’s called Method Hiding, not Overriding. Example: class Parent { static void display() { System.out.println("Static method from Parent"); } } class Child extends Parent { static void display() { System.out.println("Static method from Child"); } } public class Main { public static void main(String[] args) { Parent p = new Child(); p.display(); // Output: Static method from Parent } } 🧠 Why it Happens Because static methods belong to the class, not the object. Overriding is a runtime concept — it depends on the object type. Static methods are resolved at compile-time, based on the reference type. So in the example above, p.display() calls Parent.display() — even though p refers to a Child object. 💬 Interview Tip If the interviewer asks — “Can we override static methods?” You can confidently say: “No, static methods are hidden, not overridden — because they are resolved at compile time based on reference type, not object type.” ✅ ✨ Pro Tip: Try adding @Override before a static method — you’ll see the compiler won’t allow it. That’s your proof! #Java #100DaysOfJava #JavaInterview #StaticMethod #OOPs #MethodHiding #LearningJava #AshutoshTiwari #CleanCode #InterviewPreparation #Programming #Java #JavaDeveloper #CodingTips #SoftwareEngineering #CleanCode #TechCommunity #Java #Programming #SpringBoot #CodingTips #SoftwareEngineering #SoftwareDevelopment #JavaProgramming #CleanCode #CodingCommunity #BackendDevelopment #LearnToCode #ObjectOrientedProgramming #ProgrammingTips #HappyLearning #HappyCoding
Can We Override Static Methods in Java?
More Relevant Posts
-
Basic Java Interview Q&A – Quick Guide ✅ 1. What is Java? Java is a high-level, object-oriented, platform-independent programming language. Its “Write Once, Run Anywhere” capability comes from the JVM (Java Virtual Machine). ✅ 2. What are the features of Java? Simple & Secure Object-Oriented Platform Independent (via JVM) Robust & Multithreaded High Performance (JIT Compiler) ✅ 3. Difference between JDK, JRE, and JVM? JDK (Java Development Kit) → Tools for developing Java apps (compiler, debugger, JRE) JRE (Java Runtime Environment) → Runtime environment (JVM + libraries) JVM (Java Virtual Machine) → Executes Java bytecode, platform-dependent ✅ 4. What are OOP principles in Java? Encapsulation → Data hiding via classes Inheritance → Reusing properties/methods Polymorphism → Many forms (overloading/overriding) Abstraction → Hiding implementation details ✅ 5. Difference between == and equals()? == → Compares memory references equals() → Compares values/content ✅ 6. What is String immutability in Java? Once created, a String object cannot be changed. Any modification creates a new object in the String pool. ✅ 7. What is the difference between Array and ArrayList? Array → Fixed size, stores primitives & objects ArrayList → Dynamic size, stores only objects, part of the Collections framework ✅ 8. What are access modifiers in Java? public → Accessible everywhere protected → Within package + subclasses default → Within same package private → Within same class only ✅ 9. What is Exception Handling? A mechanism to handle runtime errors using keywords: try, catch, finally, throw, throws ✅ 10. Difference between Checked & Unchecked Exceptions? Checked → Compile-time (e.g., IOException, SQLException) Unchecked → Runtime (e.g., NullPointerException, ArithmeticException) ✅ 11. What is Garbage Collection in Java? Automatic memory management that removes unused objects from the heap. ✅ 12. What is the difference between Overloading and Overriding? Overloading → Same method name, different parameters (Compile-time polymorphism) Overriding → Subclass redefines parent method (Runtime polymorphism) #Java #JavaInterview #CoreJava #BackendDevelopment #OOP #JavaBasics #100DaysOfCode #CodingInterview #Programming #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Day 18 of My Java Journey: Mastering Interfaces! 🚀 Just wrapped up a deep dive into **Java Interfaces** today, and the concept of an interface as a **"contract"** really clicked. This is a foundational topic for writing clean, flexible, and powerful Java code. 🔑Here are the key takeaways from today's class that I'm implementing in my practice: 1. **Standardization & Polymorphism:** Interfaces are the architects of code structure, enforcing **standardization** (Rule 1) and enabling powerful **polymorphism** (Rule 2). 2. **Pure Abstraction:** Methods in an interface are automatically **public, abstract, and static** (Rule 3), which means they are pure method signatures—no bodies allowed! 3. **The 'Diamond Problem' Solver:** Java supports **multiple interface implementation** (Rule 6 & 8), which solves the famous "diamond problem" that inheritance faces. This is huge for code flexibility! 4. **Special Properties:** Variables are implicitly **public static final** (Rule 10)—making them constants. Also, shoutout to **Marker Interfaces** (Rule 11) like `Serializable`, which are just empty interfaces used to signal special properties to the JVM. This concept ties so much of what I've learned together! Any senior developers or fellow students have a favourite real-world example of how interfaces drastically simplified a project? Share your thoughts below! 👇 #Java #Programming #SoftwareDevelopment #TechLearning #JavaInterfaces #OOP #ObjectOrientedProgramming #DailyLearning #Coding #TapAcademy ✨ Insights on Java Interface Concepts To help you speak confidently about these concepts in the comments or in future posts, here are some deeper insights into the key rules mentioned here: ### 1. **The Contract Analogy** 🤝 (Rules 1 & 2) * **Rule 1: An interface is like a contract...** Think of an interface like a formal agreement in the real world. If a class (the contractor) says it will implement an interface (the contract), it *must* provide a concrete implementation (the work) for *every single method* defined in that interface. This ensures **standardization** across all implementing classes. Rule 2: Interfaces promote polymorphism.** This is the ability of an object to take on many forms. If you write a method that accepts an interface type, it can then accept *any* object that implements that interface. This allows you to write generic, flexible code that works with a variety of objects, as long as they all adhere to the interface's contract. 2. **Abstraction and Access Modifiers** (Rule 3, 5, 7, & 10) * **Rule 3: Methods are automatically `public`, `abstract`.** Since an interface is all about defining a *contract* for others to implement, its methods must be visible to everyone (hence `public`) and cannot have a body (hence `abstract`). * **Rule 7: Cannot provide methods with bodies.** This is the core principle of a traditional Java interface (before Java 8 introduced default methods). It's a blueprint, not an implement
To view or add a comment, sign in
-
-
Java secrets --- Post 1: Java ka "Zero-Day Feature" - 1995 se chupa hua raaz!🤯 #Java #ProgrammingSecrets #Coding ```java // Java 1.0 ka woh feature jo documentation mein kabhi nahi aaya: static { System.out.println("Static block - main() se pehle!"); } public static void main(String[] args) { System.out.println("Main method!"); } // Output: // Static block - main() se pehle! // Main method! ``` Kyun? Static blocks class load hote hi execute hote hain! Ye feature 1995 se exist karta hai par 99%developers ko nahi pata! 💀 --- Post 2: Java ka "Time Travel" - Code future mein execute karo!⚡ #Java #Developer #CodingTips ```java public class TimeTravel { public static void main(String[] args) { // \u000d System.out.println("Ye line 2005 mein execute hogi!"); // Unicode character Java compiler ko force karta hai // line break karne ko - time travel effect! 🕰️ } } ``` Secret: Unicode characters compile-time pe process hote hain! Java creators ne ye feature intentionally nahi banaya tha!🔥 --- Post 3: Java ka "Quantum Entanglement" - Do variables ek saath change!🌌 #Java #Programming #TechSecrets ```java public class QuantumJava { static int a = 10; static int b = a; // Entangled! public static void main(String[] args) { a = 20; System.out.println(b); // 10 ❌ Not entangled! // Java variables actually entangled nahi hote // Par developers sochte hain hote hain! 😂 } } ``` Reality Check: Java mein primitive assignment copy karta hai, reference nahi! Ye misconception 80%beginners ko hota hai! 💡 --- Post 4: Java ka "Parallel Universe" - Same class different behavior!🚀 #Java #JVM #Programming ```java public class ParallelJava { public static void main(String[] args) throws Exception { ClassLoader cl1 = new CustomClassLoader(); ClassLoader cl2 = new CustomClassLoader(); Class<?> c1 = cl1.loadClass("MyClass"); Class<?> c2 = cl2.loadClass("MyClass"); System.out.println(c1 == c2); // false ✅ // Same class name, different universe! // Different classloaders = different classes! 🌍 } } ``` JVM Magic: Har classloader ek alag "universe" create karta hai! Ye advanced concept 1%Java developers ko pata hai! 💪
To view or add a comment, sign in
-
💥 Error vs Exception in Java — What Every Developer Should Know 🚀 Ever seen your Java program crash unexpectedly and wondered, “Was that an Error or an Exception?” 🤔 Let’s break it down 👇 --- ⚠️ Error Errors represent serious issues beyond the program’s control — mostly caused by the JVM or system environment. They’re not meant to be handled by developers (though you can catch them, it’s not recommended). 🧠 Key facts: Part of the java.lang.Error class. Non-recoverable (e.g., memory leaks, JVM crashes). Examples: OutOfMemoryError, StackOverflowError. public class ErrorExample { public static void main(String[] args) { try { causeError(); } catch (Error e) { System.out.println("Caught an Error: " + e.getMessage()); } } static void causeError() { causeError(); // Recursive call — StackOverflowError } } > ⚡ Even though you can catch it, don’t — it indicates something fundamentally wrong. --- 🧩 Exception Exceptions occur due to logical or runtime issues in your code that you can handle gracefully. They help you prevent a complete program crash. 🧠 Key facts: Subclasses of java.lang.Exception. Can be recovered from using try-catch. Examples: IOException, ArithmeticException, NullPointerException. public class ExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; // ArithmeticException } catch (Exception e) { System.out.println("Handled Exception: " + e.getMessage()); } finally { System.out.println("Cleanup code runs here."); } } } > ✅ Always handle exceptions to make your application stable and user-friendly. 🧠 Key Takeaway 🧾 Use Exception Handling to deal with expected issues and keep your app stable. ❌ Avoid catching Errors — they signal critical problems the JVM cannot recover from. 💬 What’s the most unexpected Exception or Error you’ve ever debugged in Java? Drop it below 👇 #Java #Programming #ExceptionHandling #ErrorVsException #Developers #JavaLearning #CodeBetter
To view or add a comment, sign in
-
-
🚀 Day 29 of 30 Days Java Challenge – Queue in Java In Java, a Queue is a collection used to hold elements before processing — it follows the FIFO (First In, First Out) principle, just like a real-world queue! 🧩 Key Points Queue is part of java.util package. Elements are added at the rear and removed from the front. Common implementations: LinkedList (basic queue) PriorityQueue (elements ordered by priority) ArrayDeque (used for both Queue and Deque) ⚙️ Common Methods Method Description add(e) / offer(e) Inserts element remove() / poll() Removes head element element() / peek() Retrieves head element without removing --- 💻 Example: Queue in Action import java.util.*; public class QueueExample { public static void main(String[] args) { Queue<String> queue = new LinkedList<>(); queue.offer("Java"); queue.offer("Python"); queue.offer("C++"); System.out.println("Queue: " + queue); System.out.println("Peek: " + queue.peek()); // See first element System.out.println("Poll: " + queue.poll()); // Remove first element System.out.println("After poll: " + queue); // PriorityQueue example PriorityQueue<Integer> pq = new PriorityQueue<>(); pq.offer(30); pq.offer(10); pq.offer(20); System.out.println("PriorityQueue: " + pq); // Sorted order } } 🧠 Output Queue: [Java, Python, C++] Peek: Java Poll: Java After poll: [Python, C++] PriorityQueue: [10, 30, 20] 🔍 Quick Tip Use LinkedList for normal queue operations. Use PriorityQueue when you need automatic ordering. ArrayDeque is the most efficient general-purpose queue/deque implementation. #30DaysOfJavaChallenge #Java #CodingChallenge #LearnJava #DSA #JavaCollections #Programmer
To view or add a comment, sign in
-
-
#DAY54 #100DaysOFCode | Java Full Stack Development #Day54 of my #100DaysOfCode – Java Topic-> Inner classes An inner class in Java is a class defined inside another class. It helps in logically grouping classes that are only used within one place, increases encapsulation, and makes the code more readable and maintainable. -> Types of Inner Classes There are four main types of inner classes in Java: 1. Non-static Inner Class (Regular Inner Class) Declared inside another class, but outside any method. It can access all members (even private ones) of the outer class. To create an object, you need an instance of the outer class. Example: 2. Static Nested Class Declared as static inside another class. It cannot access non-static members of the outer class directly. Can be created without creating an instance of the outer class. Example: class Outer { static int number = 10; static class Inner { void show() { System.out.println("Number: " + number); } } } public class Main { public static void main(String[] args) { Outer.Inner inner = new Outer.Inner(); inner.show(); } } 3. Local Inner Class Declared inside a method of the outer class. Can access local variables of the method only if they are final or effectively final. Used for limited scope purposes. Example: class Outer { void outerMethod() { int x = 5; class Inner { void innerMethod() { System.out.println("Value of x: " + x); } } Inner inner = new Inner(); inner.innerMethod(); } } public class Main { public static void main(String[] args) { new Outer().outerMethod(); } } 4. Anonymous Inner Class A class without a name, used for instant use (usually for implementing interfaces or abstract classes). Created using new keyword. Example: abstract class Greeting { abstract void sayHello(); } public class Main { public static void main(String[] args) { Greeting greet = new Greeting() { void sayHello() { System.out.println("Hello from Anonymous Inner Class!"); } }; greet.sayHello();}} ->Advantages of Inner Classes Better encapsulation — hides inner implementation details. Code organization — logical grouping of related classes. Improved readability when used properly. Easier access to outer class members. -> When to Use Inner Classes Use them when: The inner class is closely related to the outer class. It does not make sense to use the inner class independently. You want to reduce code complexity or hide helper logic. A big thanks to my mentor Gurugubelli Vijaya Kumar Sir and the 10000 Coders for constantly guiding me and helping me build a strong foundation in programming concepts. #Java #Coding #Programming #100DaysOfCode #JavaProgramming #CodeNewbie #LearnToCode #Developer #Tech #ProgrammingTips #JavaDeveloper #CodeDaily #DataStructures #CodingLife
To view or add a comment, sign in
-
🧩 20 #Java #Map #Interview #Questions 🔹 Basic Level 1. What is a Map in Java? → A Map is a collection that stores key-value pairs, where keys are unique. 2. What are the main implementations of Map in Java? → HashMap, LinkedHashMap, TreeMap, Hashtable, ConcurrentHashMap. 3. Can a Map have duplicate keys? → ❌ No, keys must be unique (latest value replaces old one). 4. Can a Map have duplicate values? → ✅ Yes, values can be duplicated. 5. What happens if you insert the same key again in a Map? → The old value is replaced with the new one. 6. What is the difference between Map and Collection? → Map stores key-value pairs, while Collection stores individual elements (List/Set). 7. What are the key differences between HashMap and Hashtable? Feature HashMap Hashtable Synchronization No Yes Null Keys/Values Allowed Not allowed Performance. Faster. Slower 8. What is the difference between HashMap and LinkedHashMap? → LinkedHashMap maintains insertion order; HashMap does not. 9. What is the difference between HashMap and TreeMap? → TreeMap stores keys in sorted order, HashMap is unordered. 10. Can we store null key or null value in Map? → HashMap allows one null key, multiple null values. TreeMap ❌ does not allow null keys 🔹 Intermediate Level 11. How does HashMap work internally? → It uses hashing: Hash code is computed for the key. Entry stored in a bucket (array + linked list/red-black tree). If hash collision → chaining or tree balancing. 12. What is load factor in HashMap? → The ratio (default 0.75) to decide when to resize the map. 13. What is initial capacity in HashMap? → Initial number of buckets (default 16). 14. What is the time complexity of get() and put() in HashMap? → Average: O(1) Worst (collision-heavy): O(n) 15. What is a collision in HashMap? How is it handled? → Two keys having the same hash → collision. It’s handled by linked list or balanced tree (since Java 8). 16. What is difference between keySet(), values(), and entrySet()? | Method | Returns | |---------|----------| | keySet() | All keys | | values() | All values | | entrySet() | All key-value pairs | 17. How to iterate through a Map in Java? for (Map.Entry<String, Integer> e : map.entrySet()) { System.out.println(e.getKey() + " : " + e.getValue()); } 18. What is ConcurrentHashMap? → A thread-safe version of HashMap — allows concurrent access without locking the entire map. 19. Why is Hashtable considered legacy? → It’s synchronized, slower, and replaced by ConcurrentHashMap. 20. What happens if two keys have the same hashCode but are not equal()? → They are stored in the same bucket, but compared using equals().
To view or add a comment, sign in
-
🗓️ Day-21: Collection Framework in Java The Collection Framework was introduced in Java 1.2 version 🧩 It is part of the java.util package 📦 and provides a set of classes and interfaces to store and manipulate groups of objects efficiently. The framework unifies different types of collections like List, Set, and Map, making them easier to use and maintain 🧠 🔹 Important Interfaces 🌀 Iterable – Root interface of the collection framework. ➤ Allows iteration using Iterator or enhanced for-each loop. 📚 Collection – Parent interface of most collection classes. ➤ Defines basic operations like add(), remove(), size(), clear(). 📋 List – Ordered collection that allows duplicate elements. ➤ Examples: ArrayList, LinkedList, Vector, Stack. 🚫 Set – Unordered collection that does not allow duplicates. ➤ Examples: HashSet, LinkedHashSet, TreeSet. 📬 Queue – Used to hold elements before processing (FIFO order). ➤ Examples: PriorityQueue, ArrayDeque. ↔️ Deque – Double-ended queue; elements can be added or removed from both ends. ➤ Example: ArrayDeque. 🔢 SortedSet – Maintains elements in sorted order. ➤ Example: TreeSet. 🗝️ Map – Stores key–value pairs. Keys are unique, values may duplicate. ➤ Examples: HashMap, LinkedHashMap, TreeMap. 📊 SortedMap – A Map that keeps its keys in sorted order. ➤ Example: TreeMap. 🕰️ Legacy Classes (Before Java 1.2) Legacy classes are the old collection classes that existed before the framework was introduced. They were later modified to fit into the new architecture. 📦 Vector – Dynamic array (synchronized). 📚 Stack – Subclass of Vector; follows LIFO (Last In First Out). 🔐 Hashtable – Similar to HashMap but synchronized. 🔁 Enumeration – Old iterator used to traverse legacy collections. 🧠 Note: Legacy classes are still supported for backward compatibility. ⚙️ Key Points ✅ The collection framework provides a common architecture for storing and manipulating data. 🧩 It is part of the java.util package. 🧮 Interfaces define different collection types, and classes provide implementations. 🧾 Generics were added in Java 1.5 to make collections type-safe. ⚠️ Legacy classes are synchronized, while most modern collection classes are not. 10000 Coders #Java #Collections #100DaysOfCoding #Day21 #CodingJourney
To view or add a comment, sign in
-
-
💡Is It Possible to Overload and Override the main() Method in Java? This is one of those Java questions that seems easy at first... but actually requires some deeper thinking ....🤔 Let me explain it step by step 👇 🔸 1️⃣ Overloading the main() method ✅ Yes, this is possible! You can write multiple main() methods that have different parameters — this follows the rules of method overloading, and it works perfectly fine. public class Demo { public static void main(String[] args) { System.out.println("Main method with String[] called"); main(5); // calling the other version } public static void main(int x) { System.out.println("Overloaded main() called with int: " + x); } } 💡 The JVM will always begin running your program from the main(String[] args) method, but you can call the other overloaded main methods yourself from inside your code. So the answer is yes — overloading is allowed, but JVM only recognizes the standard form. 🔸 2️⃣ Overriding the main() method ❌ No, this cannot be done. The reason is that main() is a static method, and static methods are tied to the class itself, not to individual objects. In Java, you cannot override static methods — you can only hide them by creating one with the same name in a child class. Here's an example 👇 class Parent { public static void main(String[] args) { System.out.println("Parent main()"); } } class Child extends Parent { public static void main(String[] args) { System.out.println("Child main()"); } } Result (when you run the Child class): ➡️ Child main() This is not overriding — it's called method hiding. #OverloadingVsOverriding #MainMethodInJava #BeyondMainMethod #JavaConcepts #DecodedInJava #LogicWithJava #JavaProgramming
To view or add a comment, sign in
-
Basic Java Interview Q&A ✅ 1. What is Java? Java is a high-level, object-oriented, platform-independent programming language. Its “Write Once, Run Anywhere” principle is powered by the Java Virtual Machine (JVM). ✅ 2. Key Features of Java Simple & Secure Object-Oriented Platform Independent (via JVM) Robust & Multithreaded High Performance (with JIT Compiler) ✅ 3. Difference Between JDK, JRE, and JVM JDK (Java Development Kit) → Includes compiler, tools, and JRE. JRE (Java Runtime Environment) → Contains JVM + core libraries. JVM (Java Virtual Machine) → Executes bytecode, platform-dependent. ✅ 4. Four OOP Principles in Java Encapsulation → Data hiding through classes. Inheritance → Reuse properties and methods. Polymorphism → One interface, multiple implementations. Abstraction → Hide implementation details, expose essential features. ✅ 5. Difference Between == and .equals() == → Compares memory references. .equals() → Compares actual values or content. ✅ 6. What is String Immutability? Strings in Java are immutable, meaning once created, they cannot be changed. Any modification results in a new String object in the memory pool. ✅ 7. What is the difference between Array and ArrayList? Array → Fixed size, can store primitives & objects ArrayList → Dynamic size, only stores objects, part of Collections framework ✅ 8. Types of Access Modifiers public → Accessible from anywhere. protected → Accessible within the same package and subclasses. default → Accessible only within the package. private → Accessible only within the same class. ✅ 9. What is Exception Handling? A mechanism to handle runtime errors using keywords: try, catch, finally, throw, and throws. ✅ 10. Checked vs. Unchecked Exceptions Checked → Compile-time (e.g., IOException, SQLException). Unchecked → Runtime (e.g., NullPointerException, ArithmeticException). ✅ 11. What is Garbage Collection? Automatic memory management that removes unused objects from the heap to free memory space. ✅ 12. What is the difference between Overloading and Overriding? Overloading → Same method name, different parameters (Compile-time polymorphism) Overriding → Subclass redefines parent class method (Runtime polymorphism) Follow me Md Shibly Sadik for more #Java #JavaInterview #CoreJava #OOP #BackendDevelopment #JavaProgramming #CodingInterview #100DaysOfCode
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