Labels

Thursday, April 14, 2022

Class and Objects in Scala (Class -36)

 Class is nothing but blueprint for creating an object.

         e.g.:- variables, function objects, methods, etc.

 A Class is one of the basic building blocks of Scala. Classes act as templates which are used to construct instances. Classes allow programmers to specify the structure of an instance (i.e. its instance variables or fields) and the behaviour of an instance (i.e. its methods and functions) separately from the instance itself. This is important, as it would be extremely time-consuming (as well as inefficient) for programmers to define each instance individually. Instead, they define classes and create instances of those classes.


 Steps to create a program inside a Class:

 Create a Class.

2)      Include Methods and Function Object (Anonymous) inside a Class.

3)      Now assign an Object to a Class. We create Object from a Class by using ‘new’ keyword.

4)      Join Method to an Object.

5)      Join Function Object (func obj.) to a main Object.

6)      Final output with the help of elements and variables.

Methods are function inside a Class.

Example:

              Class Name is sparkBook.

      Class Members are bookID, bookName, BookAuthor, etc.

      Class Method is printBookDetails()…


Here below “book” is the Object assigned to above Class. See ‘new’ keyword to class to create an object.

Now call the method (printBookDetails) through the Object (book) to get the output:


Here below:

    Def prodtm…. Is the method, while val prd…. Is the function object.



Passing Variables to a Class:


Objects in Scala:

The word “object” has a dual meaning in Scala. As with Java, you use it to refer to an instance of a class, but in Scala, object is also a keyword.

 We can assign a value to an object.


a)      We can assign an object to other object. 


b)      Objects can be passed as a parameter to a method.

c)       Objects are returned from a method or function.

No comments:

Post a Comment