1

I am having troubles related to protected access modifier.

package pack1;
public class A{
    protected void m1(){
        System.out.println("Protected method");
    }
}
package pack2;
import pack1.A;
class B extends A{
}
class C extends B{
    public static void main(String[] args){
        B b = new C();

        b.m1();// Error: method m1() is protected access  modifier in package pack 2
    }
}

Why is B class' method not accessible even though its present in same package pack 2 in which B class exit? And protected access modifier is accessable in same package so why this error occured?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • `".... even though its present in same package?"` -- please justify this, since class B and C are defined in package pack2, while class A defined in pack1. – Hovercraft Full Of Eels May 30 '19 at 00:28
  • class B and class c in same package pack2 so when i am trying to access b class method so why its not accessible. – Sagar Gupta May 30 '19 at 00:36
  • Yes I know A class method is not accessible but Class A method is inherit to class B, Now i am using m1() method of class B which is in same package – Sagar Gupta May 30 '19 at 00:45
  • package pack2; import pack1.A; public class B extends A { public static void main(String[] args) { B b = new B(); b.m1(); } } class C extends B{ public static void main(String[] args) { B b = new B(); b.m1(); } } if we run B class so it will fine but when we run C class it says CE-The method m1() from the type A is not visible. Why it says type A, after inherit it will be the method of B. – Sagar Gupta May 30 '19 at 01:15
  • OK, I see what you're getting at. I'm sorry for my confusion. – Hovercraft Full Of Eels May 30 '19 at 01:31
  • Same question with a valid answer: https://stackoverflow.com/q/30207940/522444 – Hovercraft Full Of Eels May 30 '19 at 01:32
  • Possible duplicate of [What happens to protected method of a super class in base class in Java?](https://stackoverflow.com/questions/30207940/what-happens-to-protected-method-of-a-super-class-in-base-class-in-java) – Hovercraft Full Of Eels May 30 '19 at 01:32

0 Answers0