Q 17 - Overriding Static Method & Static Variables #21
-
🚫 Can Static Variables or Methods Be Overridden? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
Great question! Let’s unravel the mystery of static variables and methods in Java—stylishly. 🌟 🚫 Can Static Variables or Methods Be Overridden?❌ Static Variables — Cannot Be Overridden
❌ Static Methods — Cannot Be Truly Overridden
✨ Quick Code Illustrationclass Parent {
static void greet() {
System.out.println("Hello from Parent");
}
}
class Child extends Parent {
static void greet() {
System.out.println("Hello from Child");
}
}
public class Demo {
public static void main(String[] args) {
Parent obj = new Child();
obj.greet(); // Prints: Hello from Parent
}
} 🔎 Even though 🌈 Summary Table
Static members are powerful in their own right, but they don’t mix with polymorphism the same way instance members do🤓 |
Beta Was this translation helpful? Give feedback.
-
🏛️ Static Variable Inheritance in Java🔹 Core Concept
✏️ Code Illustration
🧪 Output:
📌 Key Takeaways
💡 Pro Tip: Even though you can access and modify static variables from a child class, it’s clearer and better practice to do so using the class name directly, like |
Beta Was this translation helpful? Give feedback.
-
Example:class Parent {
static int count = 10;
}
class Child extends Parent {
void updateCount() {
count = 99; // changing static variable
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Before change: " + Parent.count); // 10
Child c = new Child();
c.updateCount();
System.out.println("After change: " + Parent.count); // 99
}
} Key Points:
|
Beta Was this translation helpful? Give feedback.
-
🤓 Static Variables are Hidden when Inherited?Yes, that's exactly the terminology used in Java: when a child class declares a static variable with the same name as the parent’s, the original variable is hidden, not overridden. 🕵️♂️ Let’s clarify the difference with a direct example: class Parent {
static String message = "Hello from Parent";
}
class Child extends Parent {
static String message = "Hello from Child"; // hides Parent.message
}
public class Demo {
public static void main(String[] args) {
System.out.println(Parent.message); // Prints: Hello from Parent
System.out.println(Child.message); // Prints: Hello from Child
Parent obj = new Child();
System.out.println(obj.message); // Still prints: Hello from Parent
}
} 🔍 What’s happening here?
🔄 Summary
If you'd like to see how this affects memory layout or combine it with methods for a full contrast, we can go even deeper. 🧠📊 Ready when you are! |
Beta Was this translation helpful? Give feedback.
Great question! Let’s unravel the mystery of static variables and methods in Java—stylishly. 🌟
🚫 Can Static Variables or Methods Be Overridden?
❌ Static Variables — Cannot Be Overridden
❌ Static Methods — Cannot Be Truly Overridden