Successfully reported this slideshow.
Your SlideShare is downloading. ×

Object-oriented concepts

Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Ad
Loading in …3
×

Check these out next

1 of 41 Ad

More Related Content

Slideshows for you (20)

Similar to Object-oriented concepts (20)

Advertisement

More from BG Java EE Course (20)

Recently uploaded (20)

Advertisement

Object-oriented concepts

  1. 1. Object-OrientedObject-Oriented ProgrammingProgramming ConceptsConcepts
  2. 2. ContentsContents 1.1. What is OOP?What is OOP? 2.2. Classes and ObjectsClasses and Objects 3.3. Principles of OOPPrinciples of OOP • InheritanceInheritance • AbstractionAbstraction • EncapsulationEncapsulation • PolymorphismPolymorphism 2
  3. 3. What is OOP?What is OOP?
  4. 4. What is OOP?What is OOP? • Object-oriented programming (OOP) is anObject-oriented programming (OOP) is an engineering approach for building softwareengineering approach for building software systemssystems • Based on the concepts of classes andBased on the concepts of classes and objects that are used for modeling the realobjects that are used for modeling the real world entitiesworld entities • Object-oriented programsObject-oriented programs • Consist of a group of cooperating objectsConsist of a group of cooperating objects • Objects exchange messages, for theObjects exchange messages, for the purpose of achieving a common objectivepurpose of achieving a common objective • Implemented in object-oriented languagesImplemented in object-oriented languages 4
  5. 5. OOP in a NutshellOOP in a Nutshell • A program models a world of interactingA program models a world of interacting objectsobjects • Objects create other objects and “sendObjects create other objects and “send messages” to each other (in Java, call eachmessages” to each other (in Java, call each other’s methods)other’s methods) • Each object belongs to a classEach object belongs to a class • A class defines properties of its objectsA class defines properties of its objects • The data type of an object is its classThe data type of an object is its class • Programmers write classes (and reuse existingProgrammers write classes (and reuse existing classes)classes) 5
  6. 6. What are OOP’s Claims ToWhat are OOP’s Claims To Fame?Fame? • Better suited for team developmentBetter suited for team development • Facilitates utilizing and creating reusableFacilitates utilizing and creating reusable software componentssoftware components • Easier GUI programmingEasier GUI programming • Easier software maintenanceEasier software maintenance • All modern languages are object-oriented:All modern languages are object-oriented: Java, C#, PHP, Perl, C++, ...Java, C#, PHP, Perl, C++, ... 6
  7. 7. Classes and ObjectsClasses and Objects
  8. 8. What Are Objects?What Are Objects? • Software objects model real-world objectsSoftware objects model real-world objects or abstract conceptsor abstract concepts • E.g. dog, bicycle, queueE.g. dog, bicycle, queue • Real-world objects have states andReal-world objects have states and behaviorsbehaviors • Dogs' states: name, color, breed, hungryDogs' states: name, color, breed, hungry • Dogs' behaviors: barking, fetching, sleepingDogs' behaviors: barking, fetching, sleeping 8
  9. 9. What Are Objects?What Are Objects? • How do software objects implement real-How do software objects implement real- world objects?world objects? • Use variables/data to implement statesUse variables/data to implement states • Use methods/functions to implementUse methods/functions to implement behaviorsbehaviors • An object is a software bundle of variablesAn object is a software bundle of variables and related methodsand related methods 9
  10. 10. 10 checkschecks peoplepeople shopping listshopping list …… numbersnumbers characterscharacters queuesqueues arraysarrays Things in theThings in the real worldreal world Things in the computercomputer world Objects Represent
  11. 11. ClassesClasses • Classes provide the structure forClasses provide the structure for objectsobjects • Define their prototypeDefine their prototype • Classes define:Classes define: • Set ofSet of attributesattributes • Also calledAlso called statestate • Represented by variables and propertiesRepresented by variables and properties • BehaviorBehavior • Represented by methodsRepresented by methods • A class defines the methods and types ofA class defines the methods and types of data associated with an objectdata associated with an object 11
  12. 12. ObjectsObjects • Creating an object from a class is calledCreating an object from a class is called instantiationinstantiation • AnAn objectobject is a concreteis a concrete instanceinstance of aof a particular classparticular class • Objects have stateObjects have state • Set of values associated to their attributesSet of values associated to their attributes • Example:Example: • Class: AccountClass: Account • Objects: Ivan's account, Peter's accountObjects: Ivan's account, Peter's account 12
  13. 13. Classes – ExampleClasses – Example 13 AccountAccountAccountAccount +Owner: Person+Owner: Person +Ammount: double+Ammount: double +Owner: Person+Owner: Person +Ammount: double+Ammount: double +suspend()+suspend() +deposit(sum:double)+deposit(sum:double) +withdraw(sum:double)+withdraw(sum:double) +suspend()+suspend() +deposit(sum:double)+deposit(sum:double) +withdraw(sum:double)+withdraw(sum:double) ClassClassClassClass AttributesAttributesAttributesAttributes OperationsOperationsOperationsOperations
  14. 14. Classes and Objects –Classes and Objects – ExampleExample 14 AccountAccountAccountAccount +Owner: Person+Owner: Person +Ammount: double+Ammount: double +Owner: Person+Owner: Person +Ammount: double+Ammount: double +suspend()+suspend() +deposit(sum:double)+deposit(sum:double) +withdraw(sum:double)+withdraw(sum:double) +suspend()+suspend() +deposit(sum:double)+deposit(sum:double) +withdraw(sum:double)+withdraw(sum:double) ClassClassClassClass ivanAccountivanAccountivanAccountivanAccount +Owner="Ivan Kolev"+Owner="Ivan Kolev" +Ammount=5000.0+Ammount=5000.0 +Owner="Ivan Kolev"+Owner="Ivan Kolev" +Ammount=5000.0+Ammount=5000.0 peterAccountpeterAccountpeterAccountpeterAccount +Owner="Peter Kirov"+Owner="Peter Kirov" +Ammount=1825.33+Ammount=1825.33 +Owner="Peter Kirov"+Owner="Peter Kirov" +Ammount=1825.33+Ammount=1825.33 kirilAccountkirilAccountkirilAccountkirilAccount +Owner="Kiril Kirov"+Owner="Kiril Kirov" +Ammount=25.0+Ammount=25.0 +Owner="Kiril Kirov"+Owner="Kiril Kirov" +Ammount=25.0+Ammount=25.0 ObjectObjectObjectObject ObjectObjectObjectObject ObjectObjectObjectObject
  15. 15. MessagesMessages • What is a message in OOP?What is a message in OOP? • A request for an object to perform one of itsA request for an object to perform one of its operations (methods)operations (methods) • All communication between objects is doneAll communication between objects is done via messagesvia messages 15
  16. 16. InterfacesInterfaces • Messages define the interface to the objectMessages define the interface to the object • Everything an object can do is representedEverything an object can do is represented by its message interfaceby its message interface • The interfaces provide abstractionsThe interfaces provide abstractions • You shouldn't have to know anything aboutYou shouldn't have to know anything about what is in the implementation in order to usewhat is in the implementation in order to use it (black box)it (black box) • An interface is a set of operationsAn interface is a set of operations (methods) that given object can perform(methods) that given object can perform 16
  17. 17. The Principles of OOPThe Principles of OOP
  18. 18. The Principles of OOPThe Principles of OOP • InheritanceInheritance • AbstractionAbstraction • EncapsulationEncapsulation • PolymorphismPolymorphism 18
  19. 19. InheritanceInheritance • A class canA class can extendextend another class, inheritinganother class, inheriting all its data members and methodsall its data members and methods • The child class can redefine some of theThe child class can redefine some of the parent class's members and methods and/orparent class's members and methods and/or add its ownadd its own • A class canA class can implementimplement an interface,an interface, implementing all the specified methodsimplementing all the specified methods • Inheritance implements the “is a”Inheritance implements the “is a” relationship between objectsrelationship between objects 19
  20. 20. InheritanceInheritance • TerminologyTerminology 20 subclass or derived class superclass or base class extends subinterface superinterfaceextends class interfaceimplements
  21. 21. InheritanceInheritance 21 PersonPersonPersonPerson +Name: String+Name: String +Address: String+Address: String +Name: String+Name: String +Address: String+Address: String EmployeeEmployeeEmployeeEmployee +Company: String+Company: String +Salary: double+Salary: double +Company: String+Company: String +Salary: double+Salary: double StudentStudentStudentStudent +School: String+School: String+School: String+School: String SuperclassSuperclassSuperclassSuperclass SubclassSubclassSubclassSubclassSubclassSubclassSubclassSubclass
  22. 22. Inheritance in JavaInheritance in Java • In Java, a subclass can extend only oneIn Java, a subclass can extend only one superclasssuperclass • In Java, a subinterface can extend oneIn Java, a subinterface can extend one superinterfacesuperinterface • In Java, a class can implement severalIn Java, a class can implement several interfacesinterfaces • This is Java’s form ofThis is Java’s form of multiple inheritancemultiple inheritance 22
  23. 23. Interfaces and AbstractInterfaces and Abstract Classes in JavaClasses in Java • An abstract class can have code for someAn abstract class can have code for some of its methodsof its methods • Other methods are declaredOther methods are declared abstractabstract and leftand left with no codewith no code • An interface only lists methods but doesAn interface only lists methods but does not have any codenot have any code • A concrete class may extend an abstractA concrete class may extend an abstract class and/or implement one or severalclass and/or implement one or several interfaces, supplying the code for all theinterfaces, supplying the code for all the methodsmethods 23
  24. 24. Inheritance BenefitsInheritance Benefits • Inheritance plays a dual role:Inheritance plays a dual role: • A subclass reuses the code from theA subclass reuses the code from the superclasssuperclass • A subclass inherits theA subclass inherits the data typedata type of theof the superclass (or interface) as its ownsuperclass (or interface) as its own secondary typesecondary type 24
  25. 25. Class HierarchiesClass Hierarchies • Inheritance leads to a hierarchy of classesInheritance leads to a hierarchy of classes and/or interfaces in an application:and/or interfaces in an application: 25 Game GameFor2 BoardGame Chess Backgammon Solitaire
  26. 26. InheritanceInheritance • An object of a class at the bottom of aAn object of a class at the bottom of a hierarchy inherits all the methods of all thehierarchy inherits all the methods of all the classes aboveclasses above • It also inherits the data types of all theIt also inherits the data types of all the classes and interfaces aboveclasses and interfaces above • Inheritance is also used to extendInheritance is also used to extend hierarchies of library classeshierarchies of library classes • Allows reusing the library code andAllows reusing the library code and inheriting library data typesinheriting library data types 26
  27. 27. AbstractionAbstraction • Abstraction means ignoring irrelevantAbstraction means ignoring irrelevant features, properties, or functions andfeatures, properties, or functions and emphasizing the relevant ones...emphasizing the relevant ones... • ... relevant to the given project (with an eye... relevant to the given project (with an eye to future reuse in similar projects)to future reuse in similar projects) • Abstraction = managing complexityAbstraction = managing complexity27 ““Relevant” to what?Relevant” to what?
  28. 28. AbstractionAbstraction • Abstraction is something we do every dayAbstraction is something we do every day • Looking at an object, we see those thingsLooking at an object, we see those things about it that have meaning to usabout it that have meaning to us • We abstract the properties of the object, andWe abstract the properties of the object, and keep only what we needkeep only what we need • Allows us to represent a complex reality inAllows us to represent a complex reality in terms of a simplified modelterms of a simplified model • Abstraction highlights the properties of anAbstraction highlights the properties of an entity that we are most interested in andentity that we are most interested in and hides the othershides the others 28
  29. 29. Abstraction in JavaAbstraction in Java • In Java abstraction is achieved by use ofIn Java abstraction is achieved by use of • Abstract classesAbstract classes • InterfacesInterfaces 29
  30. 30. Abstract Data TypesAbstract Data Types • Abstract Data Types (ADT) are data typesAbstract Data Types (ADT) are data types defined by a set of operationsdefined by a set of operations • Examples:Examples: 30
  31. 31. Abstraction in AWT/SwingAbstraction in AWT/Swing • java.lang.Objectjava.lang.Object • || • +--java.awt.Component+--java.awt.Component • || • +--java.awt.Container+--java.awt.Container • || • +--javax.swing.JComponent+--javax.swing.JComponent • || • +--javax.swing.+--javax.swing.AbstractButtonAbstractButton 31
  32. 32. EncapsulationEncapsulation • Encapsulation means that all data membersEncapsulation means that all data members ((fieldsfields) of a class are declared) of a class are declared privateprivate • Some methods may be private, tooSome methods may be private, too • The class interacts with other classesThe class interacts with other classes (called the(called the clientsclients of this class) onlyof this class) only through the class’s constructors and publicthrough the class’s constructors and public methodsmethods • Constructors and public methods of a classConstructors and public methods of a class serve as theserve as the interfaceinterface to class’s clientsto class’s clients 32
  33. 33. EncapsulationEncapsulation • Ensures that structural changes remainEnsures that structural changes remain locallocal:: • Usually, the internal structure of a classUsually, the internal structure of a class changes more often than the class’schanges more often than the class’s constructors and methodsconstructors and methods • Encapsulation ensures that when fieldsEncapsulation ensures that when fields change, no changes are needed in otherchange, no changes are needed in other classes (a principle known as “locality”)classes (a principle known as “locality”) • Hiding implementation details reducesHiding implementation details reduces complexitycomplexity  easier maintenanceeasier maintenance 33
  34. 34. Encapsulation – ExampleEncapsulation – Example • Data Fields are privateData Fields are private • Constructors and accessor methods areConstructors and accessor methods are defineddefined 34
  35. 35. PolymorphismPolymorphism • Ability to take more than one formAbility to take more than one form • A class can be used through its parentA class can be used through its parent class's interfaceclass's interface • A subclass may override the implementationA subclass may override the implementation of an operation it inherits from a superclassof an operation it inherits from a superclass (late binding)(late binding) • Polymorphism allows abstract operationsPolymorphism allows abstract operations to be defined and usedto be defined and used • Abstract operations are defined in the baseAbstract operations are defined in the base class's interface and implemented in theclass's interface and implemented in the subclassessubclasses 35
  36. 36. PolymorphismPolymorphism • Why use an object as a more generic type?Why use an object as a more generic type? • To perform abstract operationsTo perform abstract operations • To mix different related types in the sameTo mix different related types in the same collectioncollection • To pass it to a method that expects aTo pass it to a method that expects a parameter of a more generic typeparameter of a more generic type • To declare a more generic field (especially inTo declare a more generic field (especially in an abstract class) which will be initializedan abstract class) which will be initialized and “specialized” laterand “specialized” later 36
  37. 37. Polymorphism – ExamplePolymorphism – Example 37 Square::calcSurface() {Square::calcSurface() { return size * size;return size * size; }} Circle::calcSurface() {Circle::calcSurface() { return PI * radius *return PI * radius * raduis;raduis; }} AbstractAbstract classclass AbstractAbstract classclass AbstractAbstract actionaction AbstractAbstract actionaction ConcreteConcrete classclass ConcreteConcrete classclass OverridenOverriden actionaction OverridenOverriden actionaction OverridenOverriden actionaction OverridenOverriden actionaction
  38. 38. PolymorphismPolymorphism • Polymorphism ensures that the appropriatePolymorphism ensures that the appropriate method is called for an object of a specificmethod is called for an object of a specific type when the object is disguised as a moretype when the object is disguised as a more generic type:generic type: 38 Figure f1 = new Square(...);Figure f1 = new Square(...); Figure f2 = new Circle(...);Figure f2 = new Circle(...); // This will call Square::calcSurface()// This will call Square::calcSurface() int surface = f1.calcSurface();int surface = f1.calcSurface(); // This will call Square::calcSurface()// This will call Square::calcSurface() int surface = f2.calcSurface();int surface = f2.calcSurface();
  39. 39. Polymorphism in JavaPolymorphism in Java • Good news: polymorphism is alreadyGood news: polymorphism is already supported in Javasupported in Java • All you have to do is use it properlyAll you have to do is use it properly • Polymorphism is implemented using aPolymorphism is implemented using a technique calledtechnique called latelate method bindingmethod binding:: • Exact method to call is determined at runExact method to call is determined at run time before performing the calltime before performing the call 39
  40. 40. QuestionsQuestions?? OOP ConceptsOOP Concepts
  41. 41. ProblemsProblems 1.1. Describe the termDescribe the term objectobject in OOP.in OOP. 2.2. Describe the termDescribe the term classclass in OOP.in OOP. 3.3. Describe the termDescribe the term interfaceinterface in OOP.in OOP. 4.4. Describe the termDescribe the term inheritanceinheritance in OOP.in OOP. 5.5. Describe the termDescribe the term abstractionabstraction in OOP.in OOP. 6.6. Describe the termDescribe the term encapsulationencapsulation in OOP.in OOP. 7.7. Describe the termDescribe the term polymorphismpolymorphism in OOP.in OOP. 41

Editor's Notes

  • The industry has embraced OOP, but no formal studies of these claimed benefits have been carried out.

×