scala Quick Start series [abstract]

        Benpian scala fast as twenty-four series of blog entry, for everyone to bring about an abstract class content.

Here Insert Picture Description


        


Abstract class

        And Java languages, scala can also be defined in the abstract class.

definition

        If a member of a class defined in the current class does not contain complete, it is an abstract class .

Incomplete definition of two situations:

  1. No method Method body ( abstract method )
  2. Uninitialized variables ( abstract field )

        The definition of abstract classes and Java, in front of the class plus the abstract keyword.
Here Insert Picture Description

Abstract method

Examples
Here Insert Picture Description

  • Design of classes, inheritance represents the above-described FIG.
  • Each form has its own method of seeking area, but different methods of calculating the area of ​​a different shape

step:

  1. Creates a Shape abstract class, an abstract method to add an area for calculating the area.
  2. Square square create a class that inherits from the Shape, which has a side length of the primary builder, and area calculation method implemented.
  3. Create a rectangle class inherits from the Shape, which has a length and width of the main structure, to achieve a method to calculate the area.
  4. Creating a circular class inherits from the Shape, which has a radius of the primary constructor, and to achieve a method to calculate the area.
  5. Write the main method, respectively, to create a square, rectangular, circular object, and print area thereof.

Reference Code:

Here Insert Picture Description


Abstract field

        In the scala, abstract fields may be defined. If a member variable is not initialized, we think it is abstract.

Syntax
Here Insert Picture Description
example

  1. Create a Person abstract class with a String abstract field WHO_AM_I
  2. Creating a Student class inherits from the Person class, rewrite WHO_AM_I field, initialized to students
  3. Creating a Student class inherits from the Person class, rewrite WHO_AM_I field, initialized to students
  4. Add the main method, create an instance of Student / Policeman, respectively, and then were printed WHO_AM_I

Reference Code
Here Insert Picture Description


        This issue of content sharing on here, like little friends remember a point like this, continued attention to the next one will bring you yo ~Anonymous inner classesIntroduction, stay tuned 9 (1> ◡ <1) 6

Here Insert Picture Description

Published 169 original articles · won praise 1392 · Views 380,000 +

Guess you like

Origin blog.csdn.net/weixin_44318830/article/details/104075129