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

Is assembly language a low level language?

491


Detail discussions on JVM, memory management and garbage collector.

550


What is the difference between method and means?

570


What does int argc char * argv [] mean?

511


What are keywords give examples?

576






What is another word for methodology?

516


Can main() method in java can return any data?

639


Give us the name of the list layoutmanagers in java?

522


Which sort is best in java?

522


What is the purpose of using javap?

610


I want to persist data of objects for later use. What’s the best approach to do so?

498


do I need to use synchronized on setvalue(int)? : Java thread

549


What java ide should I use?

561


How do you square a number in java?

546


What is meant by method?

575