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

Can java hashmap have duplicate keys?

511


Can a static class have a constructor?

522


What are kinds of processors?

571


How do you delete a list in java?

534


What is the difference between C++ and Java and your preferences?

615






How will you communicate between two applets?

632


What is a Presistent Object?

646


When is the arraystoreexception thrown?

570


What are green threads in java?

555


What is a final class ?

605


how to know the total memory occupied by the objects in the ArrayList(Array list may contain duplicate objects)

1908


How does java pattern compile work?

549


What is parsing a string?

592


What is the main functionality of the remote reference layer?

1415


Can you explain inner class.

596