Need help with embedded classes in Java

Started by
7 comments, last by GameDev.net 18 years, 7 months ago
In C++, I was able to do the following (which is now Java syntax)...

class Common
{     
    public String name;

    class Weapon
    {
        public static boolean Sword;
    }
}
PC.Weapons.Sword = true; PC (player) was a class, and Weapons was an embedded class. Sword is just a static boolean whether the player had a sword or not. I noticed that doing the same in Java is different - inner classes cannot have static variables. How can I achieve a similar result?
Advertisement
I would use an ArrayList for weapons.
Seek, and you shall find.
class Common
{
public String name;

static class Weapon
{
public static boolean Sword;
}
}
I sought, but didn't find, other than everything having to be static.

import java.lang.*;class Main{    public static void main(String args[])    {        Common PC = new Common();     }} class Common{         public static class Weapon    {        public static boolean Sword;    }}


PC can't access class Weapon. Common can, but that isn't desired, though.
AP, before you posted, I tried exactly what you did. I'm still not able to access Weapon. Error message is "unexpected type" at PC.Weapon.Sword = true; I assume that instantiated objects can't use static variables/methods/classes.
Wouldn't something simple like this suffice?


class Common
{

public String name;


class CommonWeapon
{
public boolean Sword;
}

public CommonWeapon Weapon = new Weapon();


}
Hmm, I never thought about that. After changing your line to...

public CommonWeapon Weapon = new CommonWeapon();

... it compiled. Thank you very much!
Whoops! Damn copy and paste... :P

This topic is closed to new replies.

Advertisement