How and when to use an abstract class

前端 未结 6 1578
梦毁少年i
梦毁少年i 2020-12-04 12:42

This is my test program in Java. I want to know how much abstract class is more important here and why we use abstract class for this.

Is it a mandatory or is it bes

6条回答
  •  [愿得一人]
    2020-12-04 13:33

    An abstract class is a class, which has at least one method not implemented, or the keyword abstract. For example, an abstract method may look like this:

    public abstract String myMethod(String input);

    (note that the method ends with a semi-colon).

    And a class may look like this:

    public abstract class MyClass {
    
        public abstract String myMethod(String input);
    
        public String anotherMethod(String input) {
            return intput + " additional text";
        }
    }
    

    An abstract class cannot be instantiated. Abstract classes require a subclass to implement the missing behaviour so that it can be instantiated.

    The main goal of an abstract class is to provide shared implementation of common behaviour - promoting the reuse of code.

    In Java the same effect can be achieve by using a composition of classes instead of inheritance from broadly defined abstract classes. This allows more modular, function specific classes promoting code reuse, that in turn increase maintainability.

    My advice would be to use abstract class only when strictly necessary, and in particular avoid using it as a trick bag full of all sorts of functionality.

    In Scala one would use traits, which are an elegant way to solve this. It does however, require a lot of attention to get it right through.

提交回复
热议问题