Showing posts with label Static. Show all posts
Showing posts with label Static. Show all posts

Tuesday, 17 January 2017

Can we Override static methods in java?

We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’.

If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class.


Can we overload methods that differ only by static keyword?

We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is same).


Output: Compiler Error, cannot redefine foo().


Monday, 16 January 2017

What is the difference when the synchronized keyword is applied to a static method or to a non static method?

When a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class don’t interfere with each other. It means, a thread accessing a synch non static method, and then the other thread can access the synch static method at the same time but can’t access the synch non static method.

Why Thread sleep() and yield() methods are static?

Thread sleep() and yield() methods work on the currently executing thread. So there is no point in invoking these methods on some other threads that are in wait state.

Sunday, 15 January 2017

What is the difference when the synchronized keyword is applied to a static method or to a non static method?

When a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is obtained on the class and not on the object. The lock on the object and the lock on the class don’t interfere with each other. It means, a thread accessing a synch non static method, and then the other thread can access the synch static method at the same time but can’t access the synch non static method.