Search code examples
javamultithreadinginheritanceprotectedreentrantlock

Why am i not able to use the getOwner() method of Reentrant class in subclass directly?


Im trying to use the getOwner method in the class that subclass the ReentractLock class, I know outside the package, protected methods will be available to the subclass only. So i expect the getOwner method to be available to my sublcass MyLock. But im not able to use it.

1.

public class Mylock extends ReentrantLock { }

When i use new Mylock().getOwner() I get error, getOwner is not defined.

2.

public class Mylock extends ReentrantLock {
 String getOwner() {  
 Thread t =  this.getOwner();  
 return t.getName();  
}}

Now when i use new MyLock().getOwner() it works.

My question is when i use new MyLock().getOwner() with first logic, why it shows method undefined, atleast i should get the thread object.


Solution

  • According to the documentation ReentrantLock.getOwner() is protected. When you override the method, you are giving it default access instead. For more information, read about the differences between public, protected, default, and private access levels.