Question:
Can static methods be overridable?
Answer:
No Source: CoolInterview.com
Static method cannot be overridden. Look into the following code:
package javabeat.net; public class ParentClass { public void method1(){ System.out.println("Parent Method1"); } public static void method2(){ System.out.println("Parent Method2"); } }
package javabeat.net; public class ChildClass extends ParentClass{ public void method1(){ System.out.println("Child Method1"); } public static void method2(){ System.out.println("Child Method2"); } }
package javabeat.net; public class MainClass { public static void main(String args[]){ ParentClass parent; ChildClass child = new ChildClass(); parent = child; parent.method1(); parent.method2(); } }
In the above the parent class defines two methods method1() and method2(). Here method1() is instance method and method2() defines static method. When child class trying to override th parent class method actually instance method only will be overridden. So, what happens to static method? Static methods will be hidden when you are mistakenly overriding it. when you override a method, you get the benefits of run-time polymorphism, and when you hide, you don't. That means when you call the parent.method2(), it will not call the child class method. Parent class method will be called.
Source: CoolInterview.com
Answered by: shubhi | Date: 4/4/2009
| Contact shubhi
You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override. Source: CoolInterview.com
Answered by: Sharad Singh | Date: 6/1/2009
| Contact Sharad Singh
If you have the better answer, then send it to us. We will display your answer after the approval.
Rules to Post Answers in CoolInterview.com:-
- There should not be any Spelling Mistakes.
- There should not be any Gramatical Errors.
- Answers must not contain any bad words.
- Answers should not be the repeat of same answer, already approved.
- Answer should be complete in itself.
|