I instantiate a class called Company where I have a lot of the logic of my system, I'm unsure about what visibility the following objects should have....

public class Company {

   private Scanner input = new Scanner(System.in);
   private Employee[] employee = new Employee[100];
   private Job[] job = new Job[100];


I'm almost convinced that the Scanner doesn't need to be private but I've heard everyone constantly saying "encapsulation", pretty much EVERYTHING should be declared private (apart from exceptional cases). But I'm not sure if stuff like Scanner needs to be declared private or public. The other two above I'm quite positive would be private from those listed above

5 Years
Discussion Span
Last Post by asif49

Simple rule of thumb:
Make all your variables private.
More complex real-world version of this rule:
Make all your variables private.

If, later on, you discover that other classes need some kind of access to something, create a public method.

In this particular case Scanner is a part of your user interface. That kind of console-based UI should all be in one class; if you have a Scanner used in multiple classes you lose control over the state of the Scanner - eg if you call nextInt() should you do something to move the Scanner to next line or not before some other class tries to read the next token?


Perfect answer! I thought this was the case but just needed someone's confirmation.


This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.