Define final members in Scala

Source: Internet
Author: User
Tags final inheritance modifier

To design an inheritance hierarchy at some point, you want to make sure that members are not quilt class overloaded. In Scala, as in Java, you do this by adding the final modifier to a member. For example, you could put a final modifier in front of the Arrayelement demo method, as shown in code 10.7.

Class Arrayelement extends Element {
Final Override def demo () {
println ("Arrayelement ' s implementation invoked")
}
}

Code 10.7 declaring the final method

With this version of Arrayelement, an attempt at its subclass, Lineelement, overloaded demo method, will compile however:

Elem.scala:18:error:error Overriding method Demo
In class arrayelement the type () unit;
Method Demo cannot override final
Override Def demo () {
ˆ

You may also want to make sure that the entire class has no subclasses. To do this simply declare the entire class as final by adding the final modifier to the declaration of the class. For example, code 10.8 shows how to declare arrayelement as final:

Final class Arrayelement extends Element

{
Override Def demo () {
println ("Arrayelement ' s implementation invoked")
}
}

Code 10.8 declaring final class

With this version of Arrayelement, any attempt to define subclasses will fail:

Elem.scala:18:error:

illegal inheritance from final class
Arrayelement
Class Lineelement extends Arrayelement {
ˆ

We will now remove the final modifier and demo method and return to the previously implemented element family. We will focus the rest of our chapter on completing the working version of the layout library.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.