Werner van der Merwe
Werner van der Merwe

Reputation: 39

How to make a variable accessible from a subclass but not an instance java?

I have 3 classes. In 1 class I create an instance of a subclass inheriting from a superclass. How do I make my variables accessible to my subclass without it being available to the instance of the subclass? (Like static but only over multiple classes. I am new to java so at least that is how I think.)

public class Super {
    protected int myInt; //Struggling here
}

public class Sub {
    // Like to use the myInt in the super in a method here
}

public class MainPage {
    Sub obj = new Sub();
     int x = obj.myInt; //This should not happen
}

Upvotes: 2

Views: 1324

Answers (2)

Curiosa Globunznik
Curiosa Globunznik

Reputation: 3205

Protected scope is accessible from all classes in the same package, as well as subclasses in any package. Put Super and Sub in a separate one, and you have what you want (well, if class Sub extends Super).

From your example actually it is not clear, if package private (default) scope may also suit your needs.

Upvotes: 3

Varun Mukundhan
Varun Mukundhan

Reputation: 278

Place public class MainPage in a different package and you're all set.

Upvotes: 0

Related Questions