Classes
Basic Syntax:
class Class_name{
// methods and feilds
}
Some optional attributes:
- Keyword class: A class keyword is used to declare the type of class.
- Class name: The name should begin with an initial letter (capitalized by convention).
- Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
- Traits(if any): A comma-separated list of traits implemented by the class, if any, preceded by the keyword extends. A class can implement more than one trait.
- Body: The class body is surrounded by { } (curly braces).
Object
An object consists of :
- State: It is represented by attributes of an object. It also reflects the properties of an object.
- Behavior: It is represented by methods of an object. It also reflects the response of an object with other objects.
- Identity: It gives a unique name to an object and enables one object to interact with other objects.
In Scala, an object of a class is created using the new keyword. The syntax of creating an object in Scala is:
var obj = new Objectname();
Object orientation
class C(x: R) | Constructor params - x is only available in class body. |
class C(val x: R)var c = new C(4)c.x | Constructor params - automatic public member defined. |
class C(var x: R) { assert(x > 0, "positive please") var y = x val readonly = 5 private var secret = 1 def this = this(42) } | Constructor is class body. Declare a public member. Declare a gettable but not settable member. Declare a private member. Alternative constructor. |
new { ... } | Anonymous class. |
abstract class D { ... } | Define an abstract class (non-createable). |
class C extends D { ... } | Define an inherited class. |
class D(var x: R)class C(x: R) extends D(x) | Inheritance and constructor params (wishlist: automatically pass-up params by default). |
object O extends D { ... } | Define a singleton (module-like). |
trait T { ... }class C extends T { ... }class C extends D with T { ... } | Traits. Interfaces-with-implementation. No constructor params. |
trait T1; trait T2class C extends T1 with T2class C extends D with T1 with T2 | Multiple traits. |
class C extends D { override def f = ...} | Must declare method overrides. |
new java.io.File("f") | Create object. |