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


Please Help Members By Posting Answers For Below Questions

What is style and indentation?

541


What is java lang string?

542


What is static data type in java?

534


Why is an interface be able to extend more than one interface but a class can’t extend more than one class?

697


Can we store variables in local blocks?

780






What are methods in java?

532


What are the parts of a method?

531


What happens when heap memory is full?

520


What is serialization in java?

555


Can an interface extend another interface?

588


What is the purpose of the System class?

574


Explain try and catch keywords in java?

618


Difference between string, stringbuffer and stringbuilder?

562


What is the preferred size of a component in java programming?

535


What is difference between call by value and call by reference?

493