Inheriting and overriding synchronized methods

Viewed 474

If a class has synchronized methods, does its subclass also have the same synchronized methods, whether simply inherited or overriden by the subclass?

Specifically,

  • the legacy Vector has synchronized methods, and Stack is a subclass of Vector. Does Stack also have synchronized methods?

  • the legacy Hashtable have synchronized methods, and Properties is a subclass of Hashtable. Does Properties also have synchronized methods?

Motivations of my questions are from What are the replacements for legacy collections `Stack` and `Properties`?

Thanks.

2 Answers

If a class has synchronized methods, does its subclass also have the same synchronized methods, whether simply inherited or overridden by the subclass?

A synchronized method from a super class can be overriden in a subclass as a non synchronized method and vice-versa.

If the subclass does not override a synchronized method but simply inherits it, the method will be inherited as-is as a synchronized method.

I was wondering whether we need to find synchronized replacements for Stack and Properties

Stack and Properties are thread-safe classes in the sense that most of their methods are synchronized (including the inherited methods from Vector/Hashtable). Although, that still doesn't safeguard them from being incorrectly used in a multithreaded context.

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

However, a subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass

So yes, synchronized methods are inherited by subclass. You can go through javadoc for more details.

Related