1

I am trying to understand why the protected variable in superclass is inaccessible in child class?

package pack1;

public class Parent {

    protected int r;

    public int s;
}



package pack2;

import pack1.Parent;

public class Child extends Parent {

    public static void main(String[] args) {

        Parent obj = new Child();
        obj.r = 2;      //r is not accessible here. It becomes accessible when I make it static.
        obj.s = 3;      //s is accessible.
    }
}
nabster
  • 1,561
  • 2
  • 20
  • 32
J Dev
  • 11
  • 3
  • main is a static method, not an object method. You will be able access 'r' directly from any non-static code in Child. – Tom Drake Sep 08 '18 at 05:09
  • This is called Invariance and Covariance. If you Google it, you’ll find tutorials that can explain it much better than we can in an answer here. please refer [this](https://stackoverflow.com/questions/215497/in-java-difference-between-package-private-public-protected-and-private) to understand difference between `public`, `protected` and `private` – V-rund Puro-hit Sep 08 '18 at 05:14
  • @TomDrake Thanks for the answer! So I created an instance of Parent i.e. obj...my query is why is public variable "s" is accessible but protected variable "r" is not? – J Dev Sep 08 '18 at 05:25
  • here you are using parent class instance which is base class so in different package it is not accessible.. use Child class instead of parent – vinay chhabra Sep 08 '18 at 06:04
  • @vinay chhabra Thanks Vinay! – J Dev Sep 08 '18 at 06:19
  • A method in subclass can access protected member in superclass via a subclass instance only. I refer you to JLS 6.6.2, 6.6.2.1 and 6.6.2.2 – nabster Sep 08 '18 at 06:24
  • @nabsATX Thanks! – J Dev Sep 08 '18 at 11:02
  • Why a protected member of a superclass can't be accessed from a subclass by using a superclass' reference? http://www.xyzws.com/Javafaq/why-a-protected-member-of-a-superclass-cant-be-accessed-from-a-subclass-by-using-a-superclass-reference/109 – J Dev Sep 08 '18 at 11:02

0 Answers0