What happens to protected method of a super class in base class in Java?

12,107

From JLS 6.6.2. Details on protected Access

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

Means The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

From Java Doc Controlling Access to Members of a Class
enter image description here


So you can access method m1 from class B even its not on same package because it subclass of A.
But you can't access method m1 from class C because neither its in same package as A nor its subclass of A.

So for accessing this method you can make method m1 public or move your class C into same package as class A

Share:
12,107
rock
Author by

rock

Java Developer

Updated on June 04, 2022

Comments

  • rock
    rock about 2 years

    I have a A class in package1 and B is in package2 which inherits A. A contains method m1 which is protected. Now my doubt is when I create an object of B in another class C which is also package2, the object of B is unable to access method m1 why? Below is my code

    package com.package1;
    
    public class A {
    
        protected void m1(){
            System.out.println("I'm protectd method of A");
        }
    }
    
    
    package com.package2;
    
    import com.package1.A;
    
    public class B extends A {
    
    
        public static void main(String[] args) {
    
            B b = new B();
            b.m1();          // b object able to access m1
    
        }
    
    }
    
    
    package com.package2;
    
    public class C {
    
        public static void main(String[] args) {
    
            System.out.println("Hi hello");
            B b = new B();
            b.m1(); //The method m1() from the type A is not visible
    
        }
    
    }
    

    Do protected method of super class become private in subclass?

  • rock
    rock about 9 years
    class c also in same package, what happens to method m1 in B immediately after inheriting A?
  • Sumit Singh
    Sumit Singh about 9 years
    @rock you can't access method like b.m1() in package2, you can access it only within subclass of A if its outside package1.
  • Sumit Singh
    Sumit Singh about 9 years
    See given link in answer for more details.
  • rock
    rock about 9 years
    @ Sumit Singh does m1() become private in class B?
  • Sumit Singh
    Sumit Singh about 9 years
    No like private is a keyword mean no one can access it, same protected is also keyword which mean no on can access it from outside package or outside subclass.