I have learned that in a class you can declare variables and methods. They can both be declared as static if that is prefered.
Now I have encountered a program example I do not really understand. After some variable declaration in the class there is a field declared as static and inside there is program code.
When is this code executed? My guess is that the code is executed like following when a new object is created:
- Memory allocation for the instance variables.
- Execution of the contructors connected to the instance variables.
- Exection of the static field
- Execution of the constructor (if "= new Constructor() is used when the object is created)
If I execute
MyCars myCars = new MyCars();
the following will happen in this order?
public class MyCars { private Car volvo = new Car() // (1) (2) static { volvo.setNumberOfWheels = 4; // (3) } public MyCars() { volvo.setBrand = "Volvo"; volvo.setModel = "XC70"; (4) }
Here is the original code:
public class SettingsSetter extends ListActivity { private static Map<Integer,String> menuActivities=new HashMap<Integer,String>(); private static List<BooleanSetting> settings=new ArrayList<BooleanSetting>(); static { menuActivities.put(R.id.app, Settings.ACTION_APPLICATION_SETTINGS); menuActivities.put(R.id.security, Settings.ACTION_SECURITY_SETTINGS); menuActivities.put(R.id.wireless, Settings.ACTION_WIRELESS_SETTINGS); menuActivities.put(R.id.all, Settings.ACTION_SETTINGS); settings.add(new BooleanSetting(Settings.System.INSTALL_NON_MARKET_APPS, "Allow non-Market app installs", true)); settings.add(new BooleanSetting(Settings.System.HAPTIC_FEEDBACK_ENABLED, "Use haptic feedback", false)); settings.add(new BooleanSetting(Settings.System.ACCELEROMETER_ROTATION, "Rotate based on accelerometer", false)); }
volvostatic like your real code?volvoto bestatic.