有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (4) 个答案

  1. # 1 楼答案

    如果基类有一个默认的(无参数)构造函数,如果没有显式的super()调用,它将始终被自动调用。如果可以控制基类,可以将默认构造函数设置为私有:

    public abstract class Whatever {
        private Whatever() {
            // not visible to subclasses
        }
    
        public Whatever(A a, B b, ...) {
            // this constructor must always be explicitly called by subclasses
        }
    }
    

    除此之外,您的IDE可能允许您为此打开警告。它会在选项菜单的某个地方。如果你看不到它,它就不在那里

  2. # 2 楼答案

    你可以设计一个稍微不同的方式来强化这种行为:

    超类应该是抽象的,或者至少定义final方法。然后定义一个子类必须实现的受保护方法,最后让超类在完成需要提前运行的任何代码后调用该方法:

    public abstract class SuperClass {
        // final so it can't be overriden
        public final void superMethod() {
            // required code here
    
            // then delegate to implMethod
            implMethod();
        }
    
        protected abstract() void implMethod();
    }
    
    public class SubClasss extends SuperClass {
        protected void implMethod() {
            // sub class logic
        }
    }
    

    当然,超类不必是抽象的,您可以实现implMethod,然后允许子类重写它

  3. # 3 楼答案

    我认为Chris White的答案在一般情况下是最好的。但陈颖的评论“我知道强制调用super不好。但我没有拥有super类。SDK文档要求调用super。例如link”表明它不适合这种特殊情况

    因此,我建议修改Chris White的答案,以符合具体情况

    class ChenYingTestCase extends ServiceTestCase
    {
           /**
            * Gets the current system context and stores it.
            * You can not extend this method.
            * If you want to achieve the effect of extending this method,
            * you must override chenYingSetupMethod.
            **/
           public final void setUp ( )
           {
                 super.setUp ( ) ;
                 chenYingSetup ( ) ;
           }
    
           /**
            * Does nothing (unless you extend it)
            *
            * Extend this method to do your 
            * own test initialization. If you do so, there is no need to call super.setUp() 
            * Hint:  calling super.setUp() is probably a bad idea.
            * as the first statement in your override.
            * Just put your test initialization here.
            * The real SetUp method will call super.setUp() and then this method.
            **/
           protected void chenYingSetUp ( )
           {
           }
    }
    

    然后,如果一个子类在您的控制之下,那么将其作为ChenYingTestCase的子类。如果子类不在您的控制之下,那么您不能真正强制它调用super()

  4. # 4 楼答案

    很久以前,事情变了。到目前为止(大约9年后),有一个@CallSuper注释,您可以添加基本方法,以强制覆盖此方法的任何类都必须调用super。有关更多信息,请参见here