Object Oriented Concepts – Classes

In this topic we will see Object Oriented Concepts – Classes

Defining a class

To define a class in Scala we declare keyword class in front of identifier. Class names should be capitalized.
syntax

class className

Example

class Order(orderId: Int, orderDate: String, orderCustomerId: Int, orderStatus: String) {
println("I am inside Order Constructor")
}

Disassemble and Decompile Scala code

  • Use the javap command to disassemble a .class file to look at its signature.

Syntax

:javap -p className
//In this case its Order class

Object Creation

  • To create an object in scala we use new keyword

Syntax

val or var = new className(//parameters)

Creating a function inside a class

  • We can create a function inside a class
  • In this case we create an toString function which will start with override keyword. Since toString overrides the pre-defined toString method, it has to be tagged with the override flag.
  • By using toString function we can see the details of the object instead of byte code.

Example

class Order(orderId:Int,orderDate:String,orderCustomerId:Int,orderStatus:String)
{
println("I am inside Order Constructor")
override def toString = "Order("+ orderId+ ","+ orderDate + ","+ orderCustomerId + ","+ orderStatus +")"
}

Object Creation for Order class

var order = new Order(1, "2013-10-01 00:00:00.00",100, "COMPLETE")

Passing variables in class instead of arguments
Example

class Order(val orderId:Int,val orderDate:String,val orderCustomerId:Int,val orderStatus:String) 
{
println("I am inside Order Constructor") override def toString = "Order("+ orderId+ ","+ orderDate + ","+ orderCustomerId + ","+ orderStatus +")" 
}

Object Creation for Order class

var order = new Order(1, "2013-10-01 00:00:00.00",100, "COMPLETE")

Note

  • By default if we don’t set val or var in the parameters then those are called arguments and we cannot access their elements.

Share this post