SlideShare a Scribd company logo
Introduction to

Object Oriented Programming



            Mumbai
What is an object?

       Dog


      Snowy
Dog is a generalization of Snowy


                               Dog



            Animal


                               Snowy




Subclass?
Dog



                Animal


                         Bird




Polymorphism?
object

                Real world abstractions

                      Encapsulate state
                    represent information
 state
                     Communicate by
                     Message passing
behavior
                May execute in sequence
                     Or in parallel
name




state




          behavior
inheritance       encapsulation




       Building
        blocks               polymorphism
Inheritance lets you build classes based on other
 classes, thus avoiding duplicating and repeating
                       code
When a class inherits from another,
Polymorphism allows a subclass to standin for a
                 superclass


       duck


      cuckoo
                            Bird.flapWings()

       ostrich
Encapsulation is to hide the internal
representation of the object from view outside
               object definition



                 Car.drive()
                                     Car

                                    drive()
camry
                 car
                                accord

                                          Vehicle              toyota
                 motorcycle

                              honda                 Harley-davidson

civic
                                         corolla



        5 mins
Object Oriented
Solutions


for
What the stakeholders
                         want

   1

                              Add flexibility,
                              Remove duplication
                              Encapsulation,
                 2            Inheritance,
                              Polymorphism




                     3


Apply patterns
Loose coupling
Delegation
We have a product which collects checks from
      various banks and processes them.
The process includes sending out email, a fax or
          storing a scan for the check.
Pay attention to the nouns (person, place or thing)
            they are object candidates

    The verbs would be the possible methods

          This is called textual analysis
We have a product which collects checks from
      various banks and processes them.
The process includes sending out email, a fax or
          storing a scan for the check.




       5 mins
We have a product which collects checks from
      various banks and processes them.
The process includes sending out email, a fax or
          storing a scan for the check.
FastProcessor


 process(check:Check)                       Bank
sendEmail(check:Check)
 sendFax(check:Check)
   scan(check:Check)
                          *
                             Check
                         ----------------
                          bank:Bank
object interactions
case class Bank(id:Int, name:String)
 case class Check(number:Int, bank:Bank)

 class FastProcessor {

 def process(checks:List[Check]) = checks foreach (check => sendEmail)

 def sendEmail = println("Email sent")

 }

val citibank = new Bank(1, "Citibank")          //> citibank :
com.baml.ooad.Bank = Bank(1,Citibank)
(new FastProcessor).process(List(new Check(1,citibank), new Check(2,citibank)))
                                                  //> Email sent
                                                  //| Email sent
We need to support BoA as well and that sends
                   Faxes
We dont touch the design
case class Bank(id:Int, name:String)
  case class Check(number:Int, bank:Bank)

  class FastProcessor {

  def process(checks:List[Check]) = checks foreach (check => if
(check.bank.name=="Citibank") sendEmail else sendFax)

  def sendEmail = println("Email sent")
  def sendFax = println("Fax sent")

  }

  val citibank = new Bank(1, "Citibank")          //
  val bankOfAmerica = new Bank(2, "BoA")
          //
  val citibankCheckList = List(new Check(1,citibank), new Check(2,citibank))
  val bankOfAmericaCheckList = List(new Check(1,bankOfAmerica), new
Check(2,bankOfAmerica))

  (new FastProcessor).process(citibankCheckList ::: bankOfAmericaCheckList)
                                                  //> Email sent
                                                  //| Email sent
                                                  //| Fax sent
                                                  //| Fax sent
We need to support HDFC and ICICI as well now!
good design == flexible design




whenever there is a change encapsulate it

    5 mins
What the stakeholders
                         want

   1

                              Add flexibility,
                              Remove duplication
                              Encapsulation,
                 2            Inheritance,
                              Polymorphism




                     3


Apply patterns
Loose coupling
Delegation
trait Bank {
    def process(check: Check)
  }

 object CitiBank extends Bank {
   val name = "CitiBank"
   def process(check: Check) = sendEmail
   def sendEmail = println("Email sent")

 }

 object BankOfAmerica extends Bank {
   val name = "BoA"
   def process(check: Check) = sendFax
   def sendFax = println("Fax sent")

 }

 object HDFC extends Bank {
   val name = "HDFC"
   def process(check: Check) = {sendFax; sendEmail}

     def sendEmail = println("Email sent")
     def sendFax = println("Fax sent")

 }

 case class Check(number: Int, bank: Bank)
class FastProcessor {

    def process(checks: List[Check]) = checks foreach (check =>
check.bank.process(check))

 }

  val citibankCheckList = List(new Check(1, CitiBank), new Check(2,
CitiBank))
  val bankOfAmericaCheckList = List(new Check(1, BankOfAmerica), new
Check(2, BankOfAmerica))

 val hdfcCheckList = List(new Check(1, HDFC))

  (new FastProcessor).process(citibankCheckList :::
bankOfAmericaCheckList ::: hdfcCheckList)
                                                  //>   Email sent
                                                  //|   Email sent
                                                  //|   Fax sent
                                                  //|   Fax sent
                                                  //|   Fax sent
                                                  //|   Email sent
bank
                                 FastProcessor




HDFC   BoA    Citibank


                         Check
bank
                                 FastProcessor




HDFC   BoA    Citibank


                         Check
Code to interfaces – makes software easy to
                    extend

Encapsulate what varies – protect classes from
                  changes

  Each class should have only one reason to
                   change
What the stakeholders
                         want

   1
                                Add flexibility,
                                Remove duplication
                                Encapsulation,
                                Inheritance,
                 2              Polymorphism




                     3


Apply patterns
Loose coupling
Delegation
OO Principles



result in maintenable, flexible and extensible
                  software
Open Closed Principle

Classes should be open for extension and closed
                for modification
bank




HDFC    BoA   Citibank



                         Any number of banks?
DRY

           Don't repeat yourself


All duplicate code should be encapsulated /
                 abstracted
bank
                                         FastProcessor




HDFC        BoA       Citibank


                                 Check




       CommunicationUtils
What the stakeholders
                         want

   1
                                Add flexibility,
                                Remove duplication
                                Encapsulation,
                                Inheritance,
                 2              Polymorphism




                     3


Apply patterns
Loose coupling
Delegation
Single Responsibility Principle


Each object should have only one reason to
                  change
OOPs Development with Scala
What methods should really belong to
Automobile?
OOPs Development with Scala
Liskov Substitution Principle




Subtypes MUST be substitutable for their base
                  types

      Ensures well designed inheritance
Is this valid?
class Rectangle {
   var height: Int = 0
   var width: Int = 0
   def setHeight(h: Int) = { height = h }
   def setWidth(w: Int) = { width = w }
 }

 class Square extends Rectangle {
   override def setHeight(h: Int) = { height = h; width = h }
   override def setWidth(w: Int) = { width = w; height = w }
 }

 val rectangle = new Square

 rectangle.setHeight(10)
 rectangle.setWidth(5)

  assert(10 == rectangle.height)                //>
java.lang.AssertionError: assertion failed
There are multiple options other than

             inheritance
Delegation

 When once class hands off the task of doing
           something to another

Useful when you want to use the functionality of
  another class without changing its behavior
bank




HDFC   BoA      Citibank




       We delegated processing to individual banks
Composition and Aggregation

To assemble behaviors from other classes
HDFC        BoA       Citibank




       CommunicationUtils
30 min Exercise

     Design an OO parking lot. What classes and
     functions will it have. It should say, full, empty
     and also be able to find spot for Valet parking.
     The lot has 3 different types of parking: regular,
     handicapped and compact.
OOPs Development with Scala

More Related Content

DOC
G:\Printed Ebs Exam Papers\Sec 4\Commonwealth Sec\4 8 Ct2009 (Printed)
PPT
Formal framework for semantic interoperability in Supply Chain networks
PPTX
An Automation Support for Creating Configurable Process Models
PDF
The influence of identifiers on code quality
DOC
Polimero sgiraldo
PPTX
Webquest
DOCX
15 pages report (1)
G:\Printed Ebs Exam Papers\Sec 4\Commonwealth Sec\4 8 Ct2009 (Printed)
Formal framework for semantic interoperability in Supply Chain networks
An Automation Support for Creating Configurable Process Models
The influence of identifiers on code quality
Polimero sgiraldo
Webquest
15 pages report (1)

Viewers also liked (20)

PPTX
Exclusive holiday hideaway appartment in Klosters for weekly lease
PDF
Årsberetning Destinasjon Trysil BA 2009
PPTX
Mi biografia
PDF
Effective Data Testing NPT for Final
DOCX
Yeraldo coraspe t1
PPTX
Hearst Elementary School - Update & Modernization Timeline
PDF
Healthy seedlings_manual
PDF
Registro de incidencia y mortalidad en pacientes con cáncer (RIMCAN): Informe...
PPTX
Práctica 1 jonathan moreno
PDF
Hays world 0214 vertrauen
PDF
Alcheringa ,Sponsership brochure 2011
PPTX
La importancia de la web 2.0
PPTX
TCI2013 The evolution of a tourist cluster in an urban area: the case of Fort...
DOC
Fifo pmp
PDF
H31110
PPTX
DERECHO CIVIL OBLIGACIONES VI
PPT
El aire, el viento y la arquitectura
PDF
Análisis del lenguaje y contenido emocional en #15m en Twitter
PDF
Scala style-guide
PDF
Scala traits aug24-introduction
Exclusive holiday hideaway appartment in Klosters for weekly lease
Årsberetning Destinasjon Trysil BA 2009
Mi biografia
Effective Data Testing NPT for Final
Yeraldo coraspe t1
Hearst Elementary School - Update & Modernization Timeline
Healthy seedlings_manual
Registro de incidencia y mortalidad en pacientes con cáncer (RIMCAN): Informe...
Práctica 1 jonathan moreno
Hays world 0214 vertrauen
Alcheringa ,Sponsership brochure 2011
La importancia de la web 2.0
TCI2013 The evolution of a tourist cluster in an urban area: the case of Fort...
Fifo pmp
H31110
DERECHO CIVIL OBLIGACIONES VI
El aire, el viento y la arquitectura
Análisis del lenguaje y contenido emocional en #15m en Twitter
Scala style-guide
Scala traits aug24-introduction
Ad

Similar to OOPs Development with Scala (20)

PPTX
Oop concepts
PPTX
Advanced Object-Oriented/SOLID Principles
PDF
Clean code
PDF
76829060 java-coding-conventions
PDF
Boost Your Development With Proper API Design
PPTX
Application package
PPTX
Object Oriented Programming C#
PPTX
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
PDF
Practical Type Safety in Scala
PPTX
JAVA-PPT'S-complete-chrome.pptx
PPTX
JAVA-PPT'S.pptx
PPTX
PDF
Java beginners meetup: Introduction to class and application design
PDF
Clean code
DOC
C# by Zaheer Abbas Aghani
DOC
C# by Zaheer Abbas Aghani
PPT
Java: Class Design Examples
PDF
Refactor your specs! Øredev 2013
PDF
Clean Code 2
PDF
Practical Domain-Specific Languages in Groovy
Oop concepts
Advanced Object-Oriented/SOLID Principles
Clean code
76829060 java-coding-conventions
Boost Your Development With Proper API Design
Application package
Object Oriented Programming C#
UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
Practical Type Safety in Scala
JAVA-PPT'S-complete-chrome.pptx
JAVA-PPT'S.pptx
Java beginners meetup: Introduction to class and application design
Clean code
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
Java: Class Design Examples
Refactor your specs! Øredev 2013
Clean Code 2
Practical Domain-Specific Languages in Groovy
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
PPTX
Self-Healing Test Automation Framework - Healenium
PPTX
Kanban Metrics Presentation (Project Management)
PPTX
Java 17 features and implementation.pptx
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
PPTX
GraalVM - A Step Ahead of JVM Presentation
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
Nomad by HashiCorp Presentation (DevOps)
PPTX
DAPR - Distributed Application Runtime Presentation
PPTX
Introduction to Azure Virtual WAN Presentation
PPTX
Introduction to Argo Rollouts Presentation
PPTX
Intro to Azure Container App Presentation
PPTX
Insights Unveiled Test Reporting and Observability Excellence
PPTX
Introduction to Splunk Presentation (DevOps)
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
PPTX
AWS: Messaging Services in AWS Presentation
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
PPTX
Managing State & HTTP Requests In Ionic.
Angular Hydration Presentation (FrontEnd)
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Self-Healing Test Automation Framework - Healenium
Kanban Metrics Presentation (Project Management)
Java 17 features and implementation.pptx
Chaos Mesh Introducing Chaos in Kubernetes
GraalVM - A Step Ahead of JVM Presentation
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
DAPR - Distributed Application Runtime Presentation
Introduction to Azure Virtual WAN Presentation
Introduction to Argo Rollouts Presentation
Intro to Azure Container App Presentation
Insights Unveiled Test Reporting and Observability Excellence
Introduction to Splunk Presentation (DevOps)
Code Camp - Data Profiling and Quality Analysis Framework
AWS: Messaging Services in AWS Presentation
Amazon Cognito: A Primer on Authentication and Authorization
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Managing State & HTTP Requests In Ionic.

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Machine Learning_overview_presentation.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Approach and Philosophy of On baking technology
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Network Security Unit 5.pdf for BCA BBA.
NewMind AI Weekly Chronicles - August'25-Week II
Diabetes mellitus diagnosis method based random forest with bat algorithm
Machine Learning_overview_presentation.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Machine learning based COVID-19 study performance prediction
Encapsulation_ Review paper, used for researhc scholars
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Advanced methodologies resolving dimensionality complications for autism neur...
The AUB Centre for AI in Media Proposal.docx
Unlocking AI with Model Context Protocol (MCP)
Approach and Philosophy of On baking technology
Mobile App Security Testing_ A Comprehensive Guide.pdf
MIND Revenue Release Quarter 2 2025 Press Release
20250228 LYD VKU AI Blended-Learning.pptx
“AI and Expert System Decision Support & Business Intelligence Systems”
The Rise and Fall of 3GPP – Time for a Sabbatical?

OOPs Development with Scala

  • 1. Introduction to Object Oriented Programming Mumbai
  • 2. What is an object? Dog Snowy
  • 3. Dog is a generalization of Snowy Dog Animal Snowy Subclass?
  • 4. Dog Animal Bird Polymorphism?
  • 5. object Real world abstractions Encapsulate state represent information state Communicate by Message passing behavior May execute in sequence Or in parallel
  • 6. name state behavior
  • 7. inheritance encapsulation Building blocks polymorphism
  • 8. Inheritance lets you build classes based on other classes, thus avoiding duplicating and repeating code
  • 9. When a class inherits from another, Polymorphism allows a subclass to standin for a superclass duck cuckoo Bird.flapWings() ostrich
  • 10. Encapsulation is to hide the internal representation of the object from view outside object definition Car.drive() Car drive()
  • 11. camry car accord Vehicle toyota motorcycle honda Harley-davidson civic corolla 5 mins
  • 13. What the stakeholders want 1 Add flexibility, Remove duplication Encapsulation, 2 Inheritance, Polymorphism 3 Apply patterns Loose coupling Delegation
  • 14. We have a product which collects checks from various banks and processes them. The process includes sending out email, a fax or storing a scan for the check.
  • 15. Pay attention to the nouns (person, place or thing) they are object candidates The verbs would be the possible methods This is called textual analysis
  • 16. We have a product which collects checks from various banks and processes them. The process includes sending out email, a fax or storing a scan for the check. 5 mins
  • 17. We have a product which collects checks from various banks and processes them. The process includes sending out email, a fax or storing a scan for the check.
  • 18. FastProcessor process(check:Check) Bank sendEmail(check:Check) sendFax(check:Check) scan(check:Check) * Check ---------------- bank:Bank
  • 20. case class Bank(id:Int, name:String) case class Check(number:Int, bank:Bank) class FastProcessor { def process(checks:List[Check]) = checks foreach (check => sendEmail) def sendEmail = println("Email sent") } val citibank = new Bank(1, "Citibank") //> citibank : com.baml.ooad.Bank = Bank(1,Citibank) (new FastProcessor).process(List(new Check(1,citibank), new Check(2,citibank))) //> Email sent //| Email sent
  • 21. We need to support BoA as well and that sends Faxes
  • 22. We dont touch the design
  • 23. case class Bank(id:Int, name:String) case class Check(number:Int, bank:Bank) class FastProcessor { def process(checks:List[Check]) = checks foreach (check => if (check.bank.name=="Citibank") sendEmail else sendFax) def sendEmail = println("Email sent") def sendFax = println("Fax sent") } val citibank = new Bank(1, "Citibank") // val bankOfAmerica = new Bank(2, "BoA") // val citibankCheckList = List(new Check(1,citibank), new Check(2,citibank)) val bankOfAmericaCheckList = List(new Check(1,bankOfAmerica), new Check(2,bankOfAmerica)) (new FastProcessor).process(citibankCheckList ::: bankOfAmericaCheckList) //> Email sent //| Email sent //| Fax sent //| Fax sent
  • 24. We need to support HDFC and ICICI as well now!
  • 25. good design == flexible design whenever there is a change encapsulate it 5 mins
  • 26. What the stakeholders want 1 Add flexibility, Remove duplication Encapsulation, 2 Inheritance, Polymorphism 3 Apply patterns Loose coupling Delegation
  • 27. trait Bank { def process(check: Check) } object CitiBank extends Bank { val name = "CitiBank" def process(check: Check) = sendEmail def sendEmail = println("Email sent") } object BankOfAmerica extends Bank { val name = "BoA" def process(check: Check) = sendFax def sendFax = println("Fax sent") } object HDFC extends Bank { val name = "HDFC" def process(check: Check) = {sendFax; sendEmail} def sendEmail = println("Email sent") def sendFax = println("Fax sent") } case class Check(number: Int, bank: Bank)
  • 28. class FastProcessor { def process(checks: List[Check]) = checks foreach (check => check.bank.process(check)) } val citibankCheckList = List(new Check(1, CitiBank), new Check(2, CitiBank)) val bankOfAmericaCheckList = List(new Check(1, BankOfAmerica), new Check(2, BankOfAmerica)) val hdfcCheckList = List(new Check(1, HDFC)) (new FastProcessor).process(citibankCheckList ::: bankOfAmericaCheckList ::: hdfcCheckList) //> Email sent //| Email sent //| Fax sent //| Fax sent //| Fax sent //| Email sent
  • 29. bank FastProcessor HDFC BoA Citibank Check
  • 30. bank FastProcessor HDFC BoA Citibank Check
  • 31. Code to interfaces – makes software easy to extend Encapsulate what varies – protect classes from changes Each class should have only one reason to change
  • 32. What the stakeholders want 1 Add flexibility, Remove duplication Encapsulation, Inheritance, 2 Polymorphism 3 Apply patterns Loose coupling Delegation
  • 33. OO Principles result in maintenable, flexible and extensible software
  • 34. Open Closed Principle Classes should be open for extension and closed for modification
  • 35. bank HDFC BoA Citibank Any number of banks?
  • 36. DRY Don't repeat yourself All duplicate code should be encapsulated / abstracted
  • 37. bank FastProcessor HDFC BoA Citibank Check CommunicationUtils
  • 38. What the stakeholders want 1 Add flexibility, Remove duplication Encapsulation, Inheritance, 2 Polymorphism 3 Apply patterns Loose coupling Delegation
  • 39. Single Responsibility Principle Each object should have only one reason to change
  • 41. What methods should really belong to Automobile?
  • 43. Liskov Substitution Principle Subtypes MUST be substitutable for their base types Ensures well designed inheritance
  • 45. class Rectangle { var height: Int = 0 var width: Int = 0 def setHeight(h: Int) = { height = h } def setWidth(w: Int) = { width = w } } class Square extends Rectangle { override def setHeight(h: Int) = { height = h; width = h } override def setWidth(w: Int) = { width = w; height = w } } val rectangle = new Square rectangle.setHeight(10) rectangle.setWidth(5) assert(10 == rectangle.height) //> java.lang.AssertionError: assertion failed
  • 46. There are multiple options other than inheritance
  • 47. Delegation When once class hands off the task of doing something to another Useful when you want to use the functionality of another class without changing its behavior
  • 48. bank HDFC BoA Citibank We delegated processing to individual banks
  • 49. Composition and Aggregation To assemble behaviors from other classes
  • 50. HDFC BoA Citibank CommunicationUtils
  • 51. 30 min Exercise Design an OO parking lot. What classes and functions will it have. It should say, full, empty and also be able to find spot for Valet parking. The lot has 3 different types of parking: regular, handicapped and compact.