Understanding java's protected modifier

后端 未结 6 2164
感情败类
感情败类 2020-11-22 06:45

I have a class called A in package1 and another class called C in package2. Class C extends class A.

A has an instance variable which is declared like this:

<
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 07:33

    Since C is inheriting A, C can directly use the protected variable of A like below

    public class C extends A{
    
        public void go(){
    
           System.out.println(protectedInt);
    
        }
    }
    

    As per your code, you are creating an instance of A and accessing protected variable through that instance, which violates java's rule - A protected variable is not visible outside the package

提交回复
热议问题