Knowledge Points:
1. Simple class and no parameter method
class Counter { private// must initialize field // method default is public def Current () = value}
In Scala, a class does not declare that a Public,scala source file can contain multiple classes, all of which have common visibility.
New // or New Counter () mycounter.increment () println (Mycounter.current ())
Call the no parameter method, you can write parentheses, or do not write. Use () for the converter method (that is, the method that alters the state of the object), for the accessor method (the method that does not alter the state of the object). You can use the style without parentheses by declaring current in a non-() way.
2. Attributes with Gettter and setter
Scala generates classes for the JVM and provides getter and setter methods for the declared fields. In Scala, getter and setter are called Age and age_= respectively, and the getter and setter methods can be redefined.
- Getter and setter methods are also private for private fields;
- If the field is Val, only the Getter method is generated;
- If you need any getter and setter, you can declare the field as Private[this].
The inventor of the influential Eiffel language, Bertrand Meyer, puts forward the "Unified access Principle": all services provided by a module should be accessible through a unified representation, as far as they are achieved through storage or computation, from which access should be unknown. Scala conforms to this principle.
3. Properties with Getter only
If the value of the property does not change after the object is built, the Val field can be used, and Scala generates a private final field and getter method. To summarize, there are four choices when implementing a property:
- var Foo:scala automatically synthesizes a getter and setter method
- Val Foo:scala automatically synthesizes a getter
- You define the Foo and foo_= methods.
- You define the Foo method.
When you see the field in the Scala class, it represents a private field plus the Getter method (for the Val field) or Getter and setter methods (for the Var field).
4. Object Private Fields
Private[this] When a field is modified, an object is indicated by the. Value such that access is not allowed. The method defined by a class can only access the value field of the current object, and it cannot access fields of other objects of the same class, and such access is referred to as private to the object.
Scala generates private getter and setter methods for class-private fields, and Scala does not generate getter and setter methods for fields that are private to the object.
5.Bean Properties
When you label a Scala field as @beanproperty, a method such as Getfoo/setfoo is automatically generated.
Scala fields |
The generated method |
When to use |
Val/var Name |
The Public name Name_= (var only) |
Implement a property that can be publicly accessed and stored as a field behind |
@BeanProperty Val/var Name |
The Public name GetName () Name_= (var only) SetName (...) (Var only) |
Interoperability with JavaBean |
Private Val/var Name |
The private name Name_= (var only) |
Methods for restricting field access to the class, just like Java, use private--unless you really need a public property |
Private[this] Val/var Name |
No |
Methods used to restrict field access to the same object are not often used |
private[class name] Val/var name |
relies on specific implementations |
Assigning access to external classes, not often |
6. Auxiliary constructors
1) The name of the auxiliary constructor is this
2) Each auxiliary constructor must begin with a call to a previously defined other auxiliary constructor or pig dog.
If no display definition is present, the main constructor automatically has a non-parametric primary constructor.
class person{ private var age = 0 private var name = "" this( name:string) { this() this. Name=name } This (name:string,age:int) { this(name) this. }}
7. Main constructor
1) The parameters of the main constructor are placed directly after the class name
2) The main constructor executes all the statements in the class definition
If there are no arguments after the class name, the class has an parameterless main constructor. You can usually use default parameters in the main constructor to avoid excessive use of the secondary constructor. Construction parameters can be normal method parameters, without Val or Var, and how such parameters are handled depends on how they are used in the class. If a parameter without Val or Var is used by at least one method, it will be upgraded to a field; otherwise, the parameter will not be saved as a field, just a normal parameter that can be accessed by code in the main constructor.
class Person (name:string,age:int) { = name + ' is ' + age + ' years old '}// Declaration and initialization of immutable field name, a GE, both fields are object-private, equivalent to the effect of the Private[this] Val field
Fields and methods generated for the main constructor parameter
Main constructor parameters |
Generated Fields/methods |
Name:string |
Object Private field, if there is no method to use then there is no such field |
Private Val/var name:string |
Private field, private Getter/setter method |
Val/var name:string |
Private field, public Getter/setter method |
@BeanProperty val/var:string |
Private fields, public version of Scala and JavaBean Getter/setter methods |
8. Nested classes
In Scala, you can almost embed any syntactic structure in any syntactic structure, define a function in any function, and define a class in a class.
Exercise: (reference URL)
1. Improve the Counter class in section 5.1 so that it does not become negative when int.maxvalue
class Counter { private// must initialize field def increment () { if (Value < int.maxvalue) { + = 1 }Else value method defaults to public def current () = value}
2. Write a BankAccount class, add the deposit and withdraw methods, and a read-only Balance property
class bankaccount{ = 0 def deposit (amount:double) {} def withdraw () {}}
3. Write a time class, add read-only properties hours and minutes, and a method that checks whether a moment is earlier than another before (Other:time): Boolean. The time object should be constructed in the new Time (hrs,min) mode. Where hrs is rendered in military time format (between 0 and 23)
class Time (Val hours:int,val minutes:int) { def before (other:time): Boolean={ < other.hours | | (Hours = = other.hours && minutes < other.minutes) } Override Def toString (): String={ + ":" + minutes }}
4. Re-implement the time class in the previous class to change the internal rendering to the number of minutes from midnight (between 0 and 24*60-1). Do not change the public interface. In other words, the client code should not be affected by your modifications
class Time (Val hours:int,val minutes:int) { def before (other:time): Boolean={ < other.hours | | (Hours = = other.hours && minutes < other.minutes) } Override Def toString (): String={ * + minutes) + "" }}
5. Create a student class that joins the read-write JavaBeans property name (type string) and ID (type long). What methods are being produced? (view with JAVAP.) Can you invoke JavaBeans's getter and setter methods in Scala? Should this be done?
Import Scala.beans.BeanProperty // The answer to the imported package scala2.11.8 does not have this class, in the API to find the package location class Student { = _ = _}
Javap–c Student View generated name () \name_=\setname () \getname () ID () \id_=\setid () \getid ()
Compiled from "Student.scala" Public classStudent { Publicjava.lang.String name (); Code:0: Aload_01:getfield #15//Field name:ljava/lang/string;4: Areturn Public voidName_$eq (java.lang.String); Code:0: Aload_01: Aload_12:putfield #15//Field name:ljava/lang/string;5:return Public voidSetName (java.lang.String); Code:0: Aload_01: Aload_12:putfield #15//Field name:ljava/lang/string;5:return Public LongID (); Code:0: Aload_01:getfield #24//Field id:j4: Lreturn Public voidId_$eq (Long); Code:0: Aload_01: Lload_12:putfield #24//Field id:j5:return Public voidSetId (Long); Code:0: Aload_01: Lload_12:putfield #24//Field id:j5:return Publicjava.lang.String getName (); Code:0: Aload_01:invokevirtual #30//Method Name: () ljava/lang/string;4: Areturn Public LonggetId (); Code:0: Aload_01:invokevirtual #33//Method ID: () J4: Lreturn PublicStudent (); Code:0: Aload_01:invokespecial #37//Method java/lang/object. " <init> ":() V4:return}
6. Provide a main constructor in the person class in Section 5.2 to convert the negative age to 0
class Person (Var age:int) { ifelse age }
7. Write a person class whose main constructor accepts a string that contains the name, space, and last name, such as new person ("Fred Smith"). Provides read-only properties FirstName and LastName. Should the main constructor parameter be a var,val or a normal parameter? Why?
Val, if it is Var, the corresponding string has get and set methods, because only provide read-only properties FirstName and LastName, cannot be assigned repeatedly.
8. Create a car class that corresponds to the manufacturer of the read-only property, the model name, the model year, and a read-write property for the license plate. Provides four groups of constructors. Each constructor FC requires that the manufacturer and model are required. Model year and license plate optional, if not filled, the model year is-1, the license plate is empty string. Which one would you choose as your main constructor? Why?
Class Car (Val maker:string,val typename:string) {
Auxiliary constructor parameters are model year, license plate, model year and license plate, do not know right.
9. Consider the following classes
Class employ (Val Name:string,var salary:double) {
def this () {This ("John Q. Public", 0.0)}
}
Override the class, use the displayed field definition, and a default main constructor. What kind of form do you prefer to use? Why?
class employ{ = "John Q. Public" = 0.0}
2
Quick Learn scala-Fifth Chapter class