1

i have seen so many examples in which we called wait() and notify() method directly like below.

class ThreadB extends Thread{
    int total;
    @Override
    public void run(){
        synchronized(this){
            for(int i=0; i<100 ; i++){
                total += i;
            }
            notify();
        }
    }
}

but in the object class, method signature of notify is defined as

public final void notify()

Can someone please explain how we can call these method directly without using an object as these methods are not defined as static.

2
  • 10
    You do have an object; it's this. Commented Sep 7, 2014 at 10:50
  • 1
    If you read first chapter in java... you will realise all classes extend Object class. So all methods are inherited of Object class Commented Sep 7, 2014 at 10:52

3 Answers 3

1

In java, each class extends class Object directly or indirectly. Thats why methods that are defined in class Object - for example- wait(), notify(), equals(), hashcode() etc are available to use.

check this :

and this

Sign up to request clarification or add additional context in comments.

Comments

0

A method invocation expression of the form MethodName ( [ArgumentList] ) invokes the method of the current class. If the method is not static, it is invoked on the current object, i.e. the object this points to. That is, the method invocation expression notify() is just a shorthand for writing this.notify().

The implementation of notify() can then query its this to find out which object's waiting threads should be notified.

Comments

0

These methods are the part of Object class(Superclass of every class), and hence these methods are getting inherited(implicitly) in all the classes that you write.

Coming to static part, calling these methods does not need them to be static as they are the part of your class, and hence when you say wait(), you actually mean its getting called on the correct object in hand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.