Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

creating an instance of a member class - how do you do it?

  Asked By: Rani    Date: Jul 16    Category: Java    Views: 754
  

Here is what I want to do:

public class Fruit {
public class SkinType {
public class Color {
.
.
.
}
}
}
.
.
.
// This is not working for me:
Fruit.SkinType.Color color = Fruit.SkinType.new Color();

what is the right syntax for creating the nested class?

Share: 

 

4 Answers Found

 
Answer #1    Answered By: Richie Smith     Answered On: Jul 16

Try:

Fruit.SkinType.Color color  = new Fruit.SkinType.Color();

For what its worth, you may want to consider not doing this as it will
severely prohibit reuse.

 
Answer #2    Answered By: Emma Brown     Answered On: Jul 16

That doesn't work. You need to do:
Fruit f = new Fruit();
Fruit.SkinType st = f.new SkinType();
Fruit.SkinType.Color = st.new Color();

which is a pain in the posterior.

But another idea strikes me:

public class  Fruit {
public class SkinType {

public class color  {
private String color;

public Color(String c) {
color = c;
}
.
.
.
}
public static Color GREEN;

static {
GREEN = new Color("GREEN");
}
}
}

> For what its worth, you may want to consider not doing this as it
will
> severely prohibit reuse.
>
> Sincerely,
> Anthony Eden

What I want to do is (in c++ terminology) have a enumerated list that
is encapsulated inside another class.

 
Answer #3    Answered By: Willie Gomez     Answered On: Jul 16

OK, I did basically what I had below but had to encaspulate color  in
its own separate class  rather than in the nested  class.

public class Color {

/**
* this is privvy to the instance
*/
private String color;

/**
* the constructor is private - I don't want just anyone creating
* colors
*/
private Color(String c) {
color = c;
}

public static final Color RED;

static {
RED = new Color("RED");
}
}


So now if you want a color:

Color c = Color.RED;

and you can't do (which is what I wanted)
Color c = new Color("RED");

I would have preferred to do this:

Fruit.Color c = Fruit.Color.RED;

but you can't have static members in nested classes.

oh well... there are times I really miss C++ :-)

 
Answer #4    Answered By: Pravat Jainukul     Answered On: Jul 16

Actually, you can by declaring that your inner class  is static.

public class Fruit {

public static class Color {

private String name;

private Color(String name) {
this.name = name;
}

public String toString() {
return name;
}

public static final Color RED = new Color("Red");

}

}

 
Didn't find what you were looking for? Find more on creating an instance of a member class - how do you do it? Or get search suggestion and latest updates.




Tagged: