Get child class name from parent

前端 未结 6 592
广开言路
广开言路 2021-02-06 21:36

I have a base class for my all of activities (ActivityBase) that itself derives from android.app.Activity. In onCreate I want to execute some conditio

6条回答
  •  逝去的感伤
    2021-02-06 22:24

    In your super class create method for the condition which is responsible for answering question - is the sub class one of the type X. In the processing logic use this method to decide which code block to execute. Each sub class can override decision method and answer as needed. As result your super class has no knowledge about sub classes and sub classes don't have to worry about the actual processing implementation.

    abstract class A {
    
        abstract boolean isItX();
    
        void doX() { ... }
    
        void doY() { ... }
    
        void process() {
            if (isItX()) {
                doX();
            } else {
                doY();
            }
        }
    }
    
    class B extends A {
        boolean isItX() {
            return true;
        }
    }
    
    class C extends A {
        boolean isItX() {
            return false;
        }
    }
    

    For more information see Hollywood Principle.

提交回复
热议问题