2

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
}
3
  • there is no inheritance in the provided example Also variables cannot be overridden only methods can be Commented Nov 27, 2019 at 11:22
  • The wording is not correct, an instance of Sub will always have access to myInt internally (if it extends Super which seems to be missing in your example). What you want is MainPage, or any other class which is not a subclass of Super, to not have access to myInt. In your example, when you do obj.myInt, it is MainPage that tries to access myInt, not obj Commented Nov 27, 2019 at 11:39
  • You may start with this one: tutorialspoint.com/java/java_inheritance.htm Commented Nov 27, 2019 at 11:41

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.