Class
A class is a user-defined blueprint or
prototype from which objects are created. Or in other words, a class combines
the fields and methods(member function which defines actions) into a single
unit. Basically, in a class constructor is used for initializing new objects,
fields are variables that provide the state of the class and its objects, and
methods are used to implement the behavior of the class and its objects.
Here is a simple class definition in Scala:
class MyClass {
}
·
Keyword
class: A
class keyword is used to declare the type class.
·
Class
name: The name
should begin with a 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).
Example :
class SmartPeople
{
// Class
variables
var
number: Int = 16
var
societyname: String = "Neelkant"
// Class
method
def
Display()
{
println("Name of the company : " + societyname);
println("Total number of SmartPeople : " + number);
}
}
object Main
{
// Main
method
def
main(args: Array[String])
{
// Class object
var
obj = new SmartPeople();
obj.Display();
}
}
Fields
A field is a variable that is accessible inside the whole
object. This is contrast to local variables, which are only accessible inside
the method in which they are declared. Here is a simple field declaration:
class MyClass {
var myField : Int
= 0;
}
This declaration defines a field of type Int and
initializes it to the value 0.
Constructors
In scala constructors are declared like this:
class MyClass {
var myField :
Int = 0;
def
this(value : Int) = {
this();
this.myField = value;
}
}
This example defines a constructor which takes a single
parameter, and assigns its value to the field myField.
Notice the = between the parameters and the constructor
body (the { ). This equals sign must be present in constructors.
Also notice the explicit call to the no-arg constructor,
this();. All constructors except the no-arg constructor must always call
another constructor in the beginning of its body.
Methods
Methods
In Scala methods in a class are defined like this:
class MyClass {
var myField = 0;
def getMyField()
: Int = {
return
this.myField;
}
}
The above example defines a method called getMyField. The
return type, Int, is declared after the method name. Inside the { and } the
method body is declared. The method currently just returns the myField field.
Notice the = sign between the Int and {. Methods that return a value should
have this equals sign there.
Here is a method that doesn't return anything, but
instead modifies the internal state (field) of the object. Notice how this
addToMyField() method does not have the equals sign, and no return type
specified.
class MyClass {
var myField =
0;
def
getMyField() : Int = { //return value
of type Integer
return
this.myField;
}
def
addToMyField(value : Int) { //not
return any value as type is not mentioned
this.myField += value;
}
}
Type
Casting in Scala
A Type casting is basically a conversion from one type to
another. In Dynamic Programming Languages like Scala, it often becomes
necessary to cast from type to another.Type Casting in Scala is done using the
asInstanceOf[] method.
Applications of asInstanceof method
This perspective is required in manifesting beans from an
application context file.
It is also used to cast numeric types.
It can even be applied in complex codes like
communicating with Java and sending it an array of Object instances.
Here, only an object of an extended(child) class can be
casted to be an object of its parent class but not vice-versa.
// Scala program of type casting
object GFG
{
// Function to
display name, value and
// class-name
of a variable
def
display[A](y:String, x:A)
{
println(y +
" = " + x + " is of type " + x.getClass.getName);
}
// Main method
def main(args:
Array[String])
{
var i:Int =
40;
var f:Float
= 6.0F;
var
d:Double = 85.2;
var c:Char
= 'c';
display("i", i);
display("f", f);
display("d", d);
display("c", c);
var i1 =
i.asInstanceOf[Char]; //Casting
var f1 =
f.asInstanceOf[Double]; //Casting
var d1 =
d.asInstanceOf[Float]; //Casting
var c1 = c.asInstanceOf[Int];
//Casting
display("i1", i1);
display("f1", f1);
display("d1", d1);
display("c1", c1);
}
}
Output:
i = 40
f = 6.0
d = 85.2
c = c
i1 = (
f1 = 6.0
d1 = 85.2
c1 = 99
Inner
class in Scala
Inner class means defining a class into another. This
feature enables the user to logically group classes that are only used in one
place, thus this increases the use of encapsulation, and create more readable
and maintainable code. In Scala, the concept of inner classes is different from
Java. Like in Java, the inner class is the member of the outer class, but in
Scala, the inner class is bound to the outer object.
Syntax:
class Outer_class{
class Inner_class{
// Code..
}
}
Code Example:
class GAG
{
// Inner class
class G1
{
var a = 0
def
method()
{
println("Welcome to inner class");
}
}
}
object Main
{
def main(args:
Array[String])
{
val obj =
new GAG();
val o = new
obj.G1;
o.method();
}
}
//Output:
Welcome to inner class
Case
Class and Case Object
A Case Class is just like a regular class, which has a
feature for modeling unchangeable data. It is also constructive in pattern
matching. It has been defined with a modifier case, due to this case keyword,
we can get some benefits to stop oneself from doing a sections of codes that
have to be included in many places with little or no alteration.
Syntax:
Case class className(parameters)
Note: The Case class has a default apply() method which
manages the construction of object.
Explanation
of Case Object
A Case Object is also like an object, which has more
attributes than a regular Object. It is a blend of both case classes and
object. A case object has some more features than a regular object.
Below two are important features of case object:
It is serializable.
It has a by default hashCode implementation.
case class Student (name:String, age:Int)
object Main
{
// Main method
def main(args:
Array[String])
{
val s1 =
Student("Umesh", 32)
// Display
parameter
println("Name is " + s1.name);
println("Age is " + s1.age);
val s2 =
s1.copy(age = 24)
// Display
copied and changed attributes
println("Copy Name is " + s2.name);
println("Change Age is " + s2.age);
}
}
Output:
Name is Umesh
Age is 32
Copy Name is Umesh
Change Age is 24
Singelton Objects
Scala classes cannot have static variables or methods.
Instead a Scala class can have what is called a singleton object, or sometime a
companion object.
A singleton object is declared using the object keyword.
Here is an example:
object Main {
def sayHi() {
println("Hi!");
}
}
This example defines a singleton object called Main. You
can call the method sayHi() like this:
Main.sayHi();
Notice how you write the full name of the object before
the method name. No object is instantiated. It is like calling a static method
in Java, except you are calling the method on a singleton object instead.
Companion Objects
When a singleton object is named the same as a class, it
is called a companion object. A companion object must be defined inside the
same source file as the class. Here is an example:
class Main {
def
sayHelloWorld() {
println("Hello World");
}
}
object Main {
def sayHi() {
println("Hi!");
}
}
In this class you can both instantiate Main and call
sayHelloWorld() or call the sayHi() method on the companion object directly,
like this:
var aMain : Main = new Main();
aMain.sayHelloWorld();
Main.sayHi();
No comments:
Post a Comment