Can static methods be overridden?
Answer Posted / coder
Remember that static methods can't be overridden! This doesn't mean they
can't be redefined in a subclass, but redefining and overriding aren't the same thing.
Let's take a look at an example of a redefined (remember, not overridden), static
method:
class Animal
{
static void doStuff()
{
System.out.print("a ");
}
}
class Dog extends Animal
{
static void doStuff()
{
// it's a redefinition,
// not an override
System.out.print("d ");
}
public static void main(String [] args)
{
Animal [] a = {new Animal(), new Dog(), new Animal()};
for(int x = 0; x < a.length; x++)
a[x].doStuff();
// invoke the static method
}
}
/*
Running this code produces the output:
a a a
*/
Here redefining means that you declare a static method with the same signature as the supper class'. So the same method in super class is redefined in the subclass. As you already know that the static methods can't be overridden so this is what you can do if you want the static method to behave differently in the subclass. But remember you can't have the polymorphism since no overridden happens.
Is This Answer Correct ? | 1 Yes | 1 No |
Post New Answer View All Answers
What is style and indentation?
What is java lang string?
What is static data type in java?
Why is an interface be able to extend more than one interface but a class can’t extend more than one class?
Can we store variables in local blocks?
What are methods in java?
What are the parts of a method?
What happens when heap memory is full?
What is serialization in java?
Can an interface extend another interface?
What is the purpose of the System class?
Explain try and catch keywords in java?
Difference between string, stringbuffer and stringbuilder?
What is the preferred size of a component in java programming?
What is difference between call by value and call by reference?