官术网_书友最值得收藏!

Abstract classes

Adding the abstract keyword in front of the class definition will mark the class as abstract. An abstract class is a partially defined class; properties and methods that have no implementation must be implemented in a derived class unless the derived class is meant to be an abstract class as well. Here is how you would define an abstract class in Kotlin:

    abstract class A { 
      abstract fun doSomething() 
    }

Unlike interfaces, you have to mark the function as abstract if you don't provide a body definition.

You cannot create an instance of an abstract class. The role of such a class is to provide a common set of methods that multiple derived classes share. The best example of such a case is the InputStream class. This will be very familiar to a developer who has already worked with Java. The JDK Documentation says:

" This   abstract class is the superclass of all classes representing an input stream of bytes. Applications that need to define a subclass of   InputStream   must always provide a method that returns the next byte of input ."

 If you look at the java.io package, you will find a few implementations for it—AudioInputStream, ByteArrayInputStream, FileInputStream, and many more. You could also provide an implementation of it.

You can inherit an A class with a function flagged as opened for being redefined (overridable, as we will see shortly) and marked as abstract in the derived class. This way, the derived class will become abstract. Any class that inherits from the derived class will need to provide an implementation, and it won't be able to access the implementation defined in the A class:

    open class AParent protected constructor() { 
      open fun someMethod(): Int = Random().nextInt() 
    } 
    abstract class DDerived : AParent() { 
      abstract override fun someMethod(): Int 
    } 
    class AlwaysOne : DDerived() { 
      override fun someMethod(): Int { 
        return 1 
      } 
    } 

The example is pretty straightforward. We have a parent class that defines someMethod, returning a random integer. A DDerived class inherits this class (please note we have to invoke the empty constructor on the parent class) and marks the method as abstract. Then, our AlwaysOne class will have to provide a function body for our method that always returns 1.

主站蜘蛛池模板: 邹城市| 屏东市| 石景山区| 勐海县| 泰兴市| 南宁市| 巴彦淖尔市| 城固县| 新和县| 彰化市| 景谷| 丰镇市| 南涧| 灵武市| 日土县| 南江县| 加查县| 广汉市| 许昌市| 深泽县| 尼勒克县| 泸水县| 彭州市| 岢岚县| 云安县| 开鲁县| 阳西县| 漳平市| 扎囊县| 恩施市| 沙河市| 新丰县| 加查县| 高碑店市| 富阳市| 华宁县| 锡林浩特市| 曲松县| 凤山市| 阜新市| 通州市|