Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: James Rivera   on Jul 31 In Java Category.

  
Question Answered By: Cais Nguyen   on Jul 31

Well for many reasons, for instance the Singleton
pattern which some of the other members have pointed
out, but I use it to simulate in C/C++'s way of doing
const.

For instance, if I want to create a color object that
contains the Red, Green, and Blue values, I would have
to do this in Java.

public class Color
{
private int red;
private int green;
private int blue;

private Color( int red, int green, int blue )
{
this.red = red;
this.green = green;
this.blue = blue;
}

public Color RED = new Color( 255, 0, 0 );
public Color GREEN = new Color( 0, 255, 0 );
public Color BLUE = new Color( 0, 0, 255 );
public Color WHITE = new Color( 0, 0, 0 );
public Color BLACK = new Color( 255, 255, 255 );

// Public getter methods
public ...

// Do not include setter methods because we don't
want to change the object's data
}

So now I can do the following in other places

Color red = Color.RED;
Color black = Color.BLACK;

Share: 

 

This Question has 28 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Why we declare the constructor private? Or get search suggestion and latest updates.


Tagged: