0

I am taking this Oracle Java training course and don't understand the provided solution. The problem asks you to rewrite Card class and Deck class using Enum.

Why does the solution refer to the Enum classes of rank and suit using the "private final" modifier?

Isn't it redundant to use "private final"?

I just had

public class Card_using_Enum {
    Rank rank;
    Suit suit;

(My rank and suit enums exist outside of this class within the package.)

instead of

public class Card3 {
    private final Rank rank;
    private final Suit suit;
keuleJ
  • 3,418
  • 4
  • 30
  • 51
StacyM
  • 1,036
  • 5
  • 23
  • 41
  • most likely don't need to access them outside the class which is why they used static. as for the use of private...http://stackoverflow.com/questions/2954793/the-use-of-private-keyword – programnub112 Aug 27 '14 at 22:35
  • I'm slowly understanding "private static"...both modifiers seemed unnecessary in the context of this exercise. rank and suit aren't being used outside of this exercise except in Card. – StacyM Aug 27 '14 at 22:39
  • 1
    You say they are using `private static` but in the code they use `private final` – kapex Aug 27 '14 at 23:11
  • Oops yes, private final. – StacyM Aug 27 '14 at 23:19

2 Answers2

3

If you check he code on the course you will notice (as your pasted code supports) that they are using private final.

Using private means that only methods inside the class can access those fields. This imposes the maximum restriction on access to the values - a good thing.

Using final means that once the values are set they can never be changed. This makes the object immutable which is a good thing because you can make many assumptions about objects of this type.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • Don't you cover the ideas behind "private" and "final" by using a seperate Enum class? – StacyM Aug 27 '14 at 23:21
  • 2
    No, the enum limits the variable's values to specific choices. Using `final` means that you can't change the rank or suit of the card after it's "printed". – chrylis -cautiouslyoptimistic- Aug 27 '14 at 23:23
  • 1
    @StacyM - An `enum`s **contents** cannot be changed once created (well actually they can but that discussion is for another day) but you can pick a different `enum` - unless it is marked `final` which nails the implementation down to the maximum. – OldCurmudgeon Aug 27 '14 at 23:30
1

No, private means private (no access outside of the class), and static means static (class variable, not instance variable). They're totally different.

You can have a public static object just fine.

class Stuff {
    public static int NUMBER_OF_STUFF = 42;
}

You should already know that non-static variables can be public/private too. It all works together.

markspace
  • 10,621
  • 3
  • 25
  • 39