Getting Started with Scala-04 classes (Class)

Source: Internet
Author: User

Create a package named Org.scala.clazz under Scala, create a Scala class named Oopinscala.scala, and add an object Oopinscala

(The picture of the package is wrong, it should be Org.scala.clazz)

Create a user class and add the name and age fields


Invokes the user class and executes



Use of Private[this]



We can see that the gender property is inaccessible, so that the contents of the definition using Private[this] can not be used externally, so it's good to start protecting.


Constructor for the class:

The main constructor uses:



Call:


From the results of the above we can find the Scala main constructor features:

1. The main constructor follows the class name directly, and the parameters in the main constructor are compiled into the fields of the class

2. When the main constructor executes, all statements in the class that are not contained in the method body are executed

If we remove the Val in front of the name in the user main constructor, run


We can find the error message as the Name field is not a member variable of the user class

So we can find the third feature of the Scala main constructor 3, the main constructor function parameter does not use VAR or val to declare the variable, the variable at this time is private[this] level, can only be used within the class

Use of the secondary constructor:

1. The subordinate constructor is declared using this

2. The secondary constructor must call the main constructor or other subordinate constructors


The result of the call is:



Getting Started with Scala-04 classes (Class)

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.