如何检查一个方法是否由孩子调用?

时间:2016-02-29 20:39:36

标签: java android

子类扩展了父类 父类有一些我不想在onCreate()中执行的代码。

我该怎么做?

父:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (!child)
        {
                ... more code ...
        }
    }
}

子:

public class SingleArticulo extends MainActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_articulo);

        ... other code ...
    }
}

1 个答案:

答案 0 :(得分:1)

使用Template Method模式。

基类:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.doMoreOnCreate()
    }

    protected void doMoreOnCreate() {
                ... more code ...
    }
}

子:

public class SingleArticulo extends MainActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_articulo);

        ... other code ...
    }

    @Override
    protected void doMoreOnCreate() {
    }
}