java force an extending class

前端 未结 6 1328
梦毁少年i
梦毁少年i 2020-12-31 00:17

In Java, can I somehow force a class that extends an abstract class to implement its constructor with a Object as a parameter?

Something like

public          


        
6条回答
  •  自闭症患者
    2020-12-31 00:45

    You can use a constructor with a parameter in your abstract class (make it protected if you want to dis-allow anonymous subclasses).

    public abstract class Points{
        protected Points(Something parameter){
            // do something with parameter
        }
    }
    

    Doing that, you force the implementing class to have an explicit constructor, as it must call the super constructor with one parameter.

    However, you cannot force the overriding class to have a constructor with parameters. It can always fake the parameter like this:

    public class ExtendPoints extends Points{
        public ExtendPoints(){
            super(something);
        }
    }
    

提交回复
热议问题