Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Private or public variables??

  1. #1
    Junior Member
    Join Date
    Jun 2009
    Thanked 0 Times in 0 Posts

    Default Private or public variables??

    I am due to submit some work on Friday. The program is comprised of about 15 classes and works fine in that it does what it is supposed to do. However, in one of the classes in particular I have a ton of public variables set at the start that other classes use. Should I encapsulate all of them? I'm not looking for improved performance, just better coding. Any criticism/suggestions welcome

  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Thanked 619 Times in 561 Posts
    Blog Entries

    Default Re: Private or public variables??

    general convention says you should encapsulate, but I think that if the variables can be set to any possible value at any time, there's nothing wrong with leaving them public. Another thing you could consider is making some variables final and then leaving them public.

    Oh, and as a side not, encapsulation should have a negligible effect on performance. If it doesn't, then usually (not always, though) that means something's wrong
    Last edited by helloworld922; September 16th, 2009 at 06:33 PM.

  3. #3
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Warrington, United Kingdom
    My Mood
    Thanked 156 Times in 152 Posts

    Default Re: Private or public variables??

    My answer would be yes, please do, its the correct thing.

    // Json

Similar Threads

  1. [SOLVED] Is "Public void closeFile()" a problem in the program for AS-Level computing project
    By muffin in forum What's Wrong With My Code?
    Replies: 2
    Last Post: August 5th, 2009, 09:12 PM
  2. [SOLVED] Difference between public and private variable and their uses
    By napenthia in forum Java Theory & Questions
    Replies: 1
    Last Post: April 22nd, 2009, 11:36 AM