Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object of a class within itself

Tags:

c#

oop

xna

hey i am thinking if i could make instance of a class with in itself...

My problem is that i ma creating 3D Spheres for planets & their moons whose data i am keeping in Object. I pass parameters to the constructor of my planet class for "Size" "Orbital Radius" "Texture" "Revolution Speed" etcetra. I Have to make another class for Moon's of Planets which is an exact duplicate of moon class.

I was thinking if i could make the class object within itself. Pass a parameter for list\array of Objects of itself to create and like for earth i will pass "1" to create one moon and as the moon will have the same constructor i will pass "0" for no moons of moon. to create.

Something like this

class Planet
{
    Model     u_sphere;
    Texture2D u_texture;
    //Other data members

    List<Planet> Moons = new List<Planet>(); 

    Planet()
    {
    //Default Constructor
    }

    //Overloaded\Custom Constructor
    Planet(Model m, Texture2D t, int moon_count)
    {
       u_sphere  = m;
       u_texture = t;

       while(moon_count > 0)
       {
           Model     moon_sphere = LoadMesh("moon.x");
           Texture2D u_texture   = LoadTexture("moon.bmp"); 
           Planet    temp        = new Planet(moon_sphere,moon_texture,0);
           Moons.Add(temp);
           moon_count--;
       }
    }
    //Others Getters & Setters
}
  • Is it some how possible?

  • or What is the best-practice\approach to this kind of problem?

p.s I am using C# & Microsoft X.N.A Framework

like image 385
Moon Avatar asked May 12 '11 13:05

Moon


1 Answers

Yes, why not? But you may want to make an base-class of type CelestialBody from which both your Planet and Moon classes will inhert. And you don't have to pass a Planet's Moons into the constructor, but you can just make Planet look like this:

public class Moon : CelestialBody
{
    //Moon-only properties here.
}

public class Planet : CelestialBody
{
    //Planet-only properties here.
    public List<Moon> Moons { get; set; }
}

And then add Moons like this:

myPlanet.Moons.Add(new Moon(...));

E.g. abstract-away some of the information since a Moon is not a Planet.

like image 195
Josh M. Avatar answered Oct 25 '22 05:10

Josh M.