may be its too simple but I couldnt find the right way.
In C++ I can write initWithParameter: xxx to instantiate a class and then in the init set some instance variables given the value at init time.
In Java I don’t know how to do that. Currently I do the following:
public class SpecialScreen extends BASEScreen{
private static final int ACTIVITY_1 = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //create the instance
defineScreenType (ACTIVITY_1); //second call to set the instance variable
presentOnScreen();
}
While in BASEScreen:
public class BASEScreen extends Activity {
private Integer activityCode; // which activity should I do?
@Override
public void onCreate(Bundle savedInstanceState) { // the creation
super.onCreate(savedInstanceState);
}
// the setting of the instance variable
public void defineScreenType(int screenID) {
activityCode = screenID;
}
This can’t be the best way of doing it. How to do this better?
Thanks
ADDED to show the calling of the SpecialScreen within BASEScreen:
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
Intent i;
switch (item.getItemId()) {
case OTHER_PAGE_ID:
//
if (activityCode == ACTIVITY_1) {
i = new Intent(this, SpecialScreen2.class);
i.putExtra("Task", ACTIVITY_2);
startActivityForResult(i, ACTIVITY_2);
finish();
} else {
i = new Intent(this, SpecialScreen1.class);
i.putExtra("Task", ACTIVITY_1);
startActivityForResult(i, ACTIVITY_1);
finish();
}
return true;
ps I know that putting the Extra is not required anymore. This was the way I did it before I had the two SpecialScreen subclasses and always called the BASEScreen with this parameter.
Correct, there is no “default” syntax like in c++. You have to do it in the constructor. Mind you, you don’t need to use the setter method, you could make
activityCodeprotected rather than private, and just do:The other option is using the Builder Pattern to construct your objects, using a set of defaults inside the builder that you override (when needed) when requesting the object be built.
Edit in response to comments below:
I apologize for some confusion as I was calling it a “constructor” when it’s not.
If in
BASEScreenyou change the access toprotectedfromprivateYou can then access that in the
SpecialScreensubclass: