educative.io

Protecteed access modifier

I have modified the Thief class by making it extends the Cop class. now since Thief is a subclass of the Cop class, eventhough the fire method in the Cop class is protected. there should not be compile time error.
package crime;
import justice.*;

class Thief extends Cop{  
  public static void main(String args[]){  
   Cop obj = new Cop();  
   obj.fire(); //Compile Time Error  
  }  
}  

Thief.java:7: error: fire() has protected access in Cop
obj.fire(); //Compile Time Error
^
1 error

Why i am getting this error.??


Course: Learn Object-Oriented Programming in Java - Learn Interactively
Lesson: Access Modifiers - Learn Object-Oriented Programming in Java

Hi rajan_kumar_jha,
It would create an error even if you protected the method of subclass. You should make it public to use in another class.

I hope you get my point. Let me know of any further confusion.

It gives you an error since you are trying to access the fire method using object reference.


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers