0

I've been trying to create predefined classes several times in different languages but I couldn't find out how.

This is one of the ways I tried it:

public class Color{
    public float r;
    public float r;
    public float r;

    public Color(float _r, float _g, float _b){
        r = _r;
        g = _g;
        b = _b;
    }
    public const Color red = new Color(1,0,0);
}

This is in C# but I need to do the same in Java and C++ too so unless the solution is the same I would like to know how to do it in all of those.

EDIT: that code did not work, so the question was for all three languages.I got working answers for C# and Java now and I guess C++ works the same way, so thanks!

David
  • 156
  • 1
  • 1
  • 10
  • 3
    Actually that **is not** C# (member must be readonly, not const). Anyway syntax (of course because they're different languages) varies but concept is the same (in this case). – Adriano Repetti Mar 26 '14 at 10:17
  • That was the problem, changed it to public static readonly and now it works! – David Mar 26 '14 at 10:20

3 Answers3

3

In Java you could use an enum to accomplish this.

enum Colour
{
    RED(1,0,0), GREEN(0,1,0);

    private int r;
    private int g;
    private int b;

    private Colour( final int r, final int g, final int b )  
    {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    public int getR()
    {
        return r;
    }

    ... 
}
Zyn
  • 614
  • 3
  • 10
2

I think a good way in C++ is use static members :

// Color.hpp
class Color
{
  public:
    Color(float r_, float g_, float b_) : r(r_), g(g_), b(b_) {}
  private: // or not...
    float r;
    float g;
    float b;

  public:
    static const Color RED;
    static const Color GREEN;
    static const Color BLUE;
};

// Color.cpp
const Color Color::RED(1,0,0);
const Color Color::GREEN(0,1,0);
const Color Color::BLUE(0,0,1);

In your code, you access them like Color c = Color::RED;

Caduchon
  • 4,574
  • 4
  • 26
  • 67
1

Java is very similar

public class Color {
    //If you really want to access these value, add get and set methods.
    private float r;
    private float r;
    private float r;

    public Color(float _r, float _g, float _b) {
        r = _r;
        g = _g;
        b = _b;
    }
    //The qualifiers here are the only actual difference. Constants are static and final.
    //They can then be accessed as Color.RED
    public static final Color RED = new Color(1,0,0);
}
Dan Temple
  • 2,736
  • 2
  • 22
  • 39