2

I have two classes in different packages as follows This is the base class in package library.

package library;

public class Book{

    public int varPublic;
    protected int varProtected;
    private int varPrivate;
    int varDefault;
}

and this is the subclass in the package building.

package building;

import library.Book;

public class StoryBook extends Book {


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Book book = new Book();
        book.varPublic = 10;
        book.varProtected = 11;


    }

}

my understanding is that the variable "var.Protected" should be visible in the class StoryBook but i am getting an error. I have tried to execute this code from eclipse and command-prompt.

could anyone please look into this

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • this.varProtected =11; //this would work fine... – Ashish Dec 12 '13 at 04:28
  • issue is the same but both the codes are different. In the other post he is using this keyword to assign a protected variable inside a constructor. But i am trying to access the protected variable directly with reference to the object. i am a beginner in java programming and this code i have written does not do what is described in the java tutorials. – user3000126 Dec 12 '13 at 05:01

1 Answers1

2

Classes in other packages that are subclasses of the declaring class can only access their own inherited protected members.

public class StoryBook extends Book {
    public StoryBook() {
        System.out.println(this.variable); // this.variable is visible
    }
}

... but not other objects' inherited protected members.

public class StoryBook extends Book {
    public StoryBook() {
        System.out.println(this.variable); // this.variable is visible
    }

    public boolean equals(StoryBook other) {
        return this.variable == other.variable; // error: StoryBook.variable is not visible
    }
}

Also take a took at this article

Why a protected member of a superclass can't be accessed from a subclass by using a superclass' reference?

Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76