Understanding java's protected modifier

后端 未结 6 2256
感情败类
感情败类 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条回答
  •  轮回少年
    2020-11-22 07:10

    Protected means :

    a)This member will be accessible to all classes in same package through A object’s reference.

    b) For different package, this will be accessible only inside Subclasses of A say B and the reference used can be of B instance or of any subclass of B.

    Let's take an example:

    Let A be parent class in some package say com.ex1 Let B ,C be classes in different package w.r.t to A say com.ex2 . Also, B extends A and C extends B. We will see how we can use protected field of A inside B (a subclass of A)

    A's code:

    public class A {
        protected int a = 10;
    }
    

    B's code:

    public class B extends A {
    
    
        public void printUsingInheritance() {
            // Using this
            System.out.println(this.a);
        }
    
    
        public void printUsingInstantiation() {
            // Using instance of B
            B b = new B();
            System.out.println(b.a);
    
            // Using instance of C as C is subclass of B
            C c = new C();
            System.out.println(c.a);
    
    
            A a = new A();
            System.out.println(a.a); // Compilation error as A is not subclass of B
        }
    }
    

    C's code:

    public class C extends B {
    
    }
    

    For protected Static :

    Same rules apply except that in b) now it is accessible in any subclass of A by A's class reference. Reference

提交回复
热议问题