Object-Oriented Core Concepts Review PDF
Document Details
Uploaded by StainlessCopper2465
UKM
Aishah Harris Tim
Tags
Related
Summary
This document reviews fundamental object-oriented programming concepts, including object, class, abstraction, encapsulation, and inheritance. It provides examples and questions to help understand these concepts. The document also discusses different types of inheritance and how to avoid re-implementing shared capabilities.
Full Transcript
Review of Object-Oriented Core Concepts 1 LIBRARY Aishah Tim Harris 2 Q1*: Can you identify how many objects involved? LIBRARY Aishah Ti...
Review of Object-Oriented Core Concepts 1 LIBRARY Aishah Tim Harris 2 Q1*: Can you identify how many objects involved? LIBRARY Aishah Tim Harris 3 Number of objects involved: 8 LIBRARY Aishah Tim Harris 4 (What you just identified) OO Concept 1: Object A software object represents a tangible or intangible thing/entity in the real world. Examples: Object has: a book a student as well as, a loan 5 LIBRARY Aishah Tim Harris 6 Q2*: Can you identify the classes (object types) involved? LIBRARY Library Librarian Aishah Book Tim Member Harris 7 (What you just identified) OO Concept 2: Class Class – the template or blueprint from which an object is actually made. Analogy: Cookie cutter - Class Cookies - Objects 8 Object(s) Class Aishah Member Harris 9 Object(s) Class Book 1 Book 2 Book Book 3 Book 4 10 Object(s) Class LIBRARY Library 11 Object(s) Class Librarian Tim 12 Q3*: Can you identify main attributes of Book object(s)? Object(s) Class Book Book 1 Book 2 title author bookID Book 3 Book 4 availability 13 Q4: Can you identify main attributes of Member object(s)? Object(s) Class Member Aishah name memberID currentBooks (0 @ 1 @ 2 @ 3 Books) Harris 14 Q5: Can you identify main attributes of Librarian object(s)? Object(s) Class Librarian Tim name staffID 15 Q6: Can you identify main attributes of Library object(s)? Object(s) Class LIBRARY Library name bookList (4 Books) memberList (2 Members) librarian (1 Librarian) 16 (What you just did) OO Concept 3: Abstraction Abstraction is capturing only the essential details about an object that are relevant to a particular perspective, and ignoring the unimportant. – For example, from a university management’s perspective, important attributes and behaviour of a student should be name, matric number and register a course. 17 Suppose the following are some attributes of a person (Josh) in the real world: Matric number Name Date of birth Email address Weight Height Faculty Study programme Josh Attributes should be abstracted to define a Student object, for Josh, in a University Management System.. 18 Matric number Name Date of birth Email address Weight Height Faculty Study programme Josh Attributes should be abstracted to define a Patient object, for Josh, in a Hospital Management System? Other than attributes/data, we also need to abstract objects’ operations 20 Q7*: Can you identify main operations of Member object(s)? Object(s) Class Member Aishah borrowBook(memberID, bookID) returnBook(memberID, bookID) searchBookByTitle(title) searchBookByAuthor(author) Harris 21 Q8: Can you identify main operations of Librarian object(s)? Object(s) Class Librarian Tim recordBookLoan(memberID, bookID) recordBookReturn(memberID, bookID) recordFinePayment(memberID, amount) 22 Q9: Can you identify main operations of Book object(s)? Object(s) Class Book Book 1 Book 2 updateAvailability(newStatus) Book 3 Book 4 23 Q10: Can you identify main operations of Library object(s)? Object(s) Class LIBRARY Library returnSearchedTitleBookList(title) returnSearchedAuthorBookList(author) 24 Q11: Can you define a Java class for this? You don’t have to implement the methods of class’s operations class Librarian { String name; String staffID; boolean recordBookLoan(String memberID, String bookID) { Librarian … } name boolean recordBookReturn(String memberID, String bookID) { … staffID } boolean recordFinePayment(String recordBookLoan(memberID, bookID) memberID, double amount) { … } recordBookReturn(memberID, bookID) } recordFinePayment(memberID, amount) 25 Q12: What would you do to improve the code? class Member { class Member { String name; private String name; String staffID; private String staffID; boolean recordBookLoan(String public boolean recordBookLoan(String memberID, String bookID) { memberID, String bookID) { … … } } boolean recordBookReturn(String public boolean recordBookReturn(String memberID, String bookID) { memberID, String bookID) { … … } } boolean recordFinePayment(String public boolean recordFinePayment(String memberID, double amount) { memberID, double amount) { … … } } } } 26 (What you just did) OO Concept 4: Encapsulation Encapsulation is the technique for packaging information in such a way as to hide what should be hidden (information hiding), and make visible what is intended to be visible. 27 Information normally hidden by objects: – Object attributes – Implementation of object behaviour The specifics of how they react to the messages received by them. HIDDEN BY OBJECT REVEALED BY OBJECT attributes: width = 20 height = 20 … getArea() behaviour: getArea() return result of width x height 28 If you have the following objects, and they can do these: Walk , jump Walk, fly, lay eggs Walk, fly, swim, lay eggs Q13*: What would you do to avoid re-implementing shared capabilities between these objects? 29 Animal OO Concept 5: Inheritance move() move = walk Bird move() move = (walk) + fly layEgg() move = (walk) + jump move = (walk + fly) + swim Generally, the subclass provides additional methods that are specific to its needs or that alter the behaviour of existing methods in the superclass (i.e. method overriding). 30 There are 5 types of inheritance: Single inheritance – when a class extends one class only. Multiple inheritance — rarely used in software projects because it creates unwanted complexity when extending the class, is when a one child class extends more than one parents class. Multilevel inheritance — when a class inherits from a derived class, thereby making the derived class the parent class of the new class. eg. Class C is a child class of child Class B, of which Class B is a child class of Class A. Hierarchical inheritance – when one class is inherited by many subclasses. Example class B, C and D inherits the same class A. A is the parent class of B, C & D. Hybrid inheritance – a combination of Single and Multiple inheritance. Note, Java does not support multiple inheritance which is a good thing because it reduces complexity and simplify the language. 31 If you put all these objects in a queue, and you call out instruction “move” to each animal in the queue, how will each animal react? Animal, move! Q14*: What is the concept that allows each sub-class of Animal to respond differently to the same instruction? 32 OO Concept 6: Polymorphism The ability of different objects to respond, each in its own way, to the same message. 33 OO Concept 6: Polymorphism Polymorphism allows a task to be performed in multiple forms or ways. It is applied to the methods. Polymorphism allows the object to decide which method to implement at compile-time as well as run- time. There are 2 types of polymorphism: 1. Compile-time polymorphism (Method overloading) 2. Run-time polymorphism (Method Overriding) 34 Compile-time polymorphism (Method overloading) Method overloading means a class has several methods with the same name but different types/order/number of parameters. For compile-time polymorphism, the method to be implemented is determined during the compilation time because during writing the code we already mention the different types of parameters for the same function name. Inheritance is not involved in compile-time polymorphism. 35 Run-time polymorphism (Method Overriding) Method overriding allows the child class to have a method with the same name as in the parent class. Run-time polymorphism allows the method of a particular object to be invoked at run time, instead of declared type while coding. 36 Object-Oriented Class Relationships Object-Oriented Class Relationships There are FOUR main types of relationship between classes in OO approach: Differences in term of: 1. Association 2. Aggregation CONCEPTS 3. Composition IMPLEMENTATION 4. Inheritance Association in Concept Association is a relationship between two objects. – The objects have an independent lifecycle, and there is no ownership between the objects. – Example: Book - Author Many Books can be written by one Author, and one Book can be written by many Authors (no ownership), but both have their own lifecycles (both can be created and deleted independently) → so when a Book is destroyed, its Author(s) does not die, and when an Author dies, their Book(s) does not just disappear. Association in Concept Association is a relationship between two objects. – The objects have an independent lifecycle, and there is no ownership between the objects. – Example: Book - Author Many Books can be written by one Author, and one Book can be written by many Authors (no ownership), but both have their own lifecycles (both can be created and deleted independently) → so when a Book is destroyed, its Author(s) does not die, and when an Author dies, their Book(s) does not just disappear. Association in Concept Association is a relationship between two objects. – The objects have an independent lifecycle, and there is no ownership between the objects. – Example: Book - Author Many Books can be written by one Author, and one Book can be written by many Authors (no ownership), but both have their own lifecycles (both can be created and deleted independently) → so when a Book is destroyed, its Author(s) does not die, and when an Author dies, their Book(s) does not just disappear. Many Books can be written by one Author, and one Book can be written by many Authors. Aggregation in Concept Aggregation is a special form of association. Aggregation refers to a has-a relationship between two objects (whole/part). – The objects have an independent lifecycle, but there is an ownership between the objects where the whole object contains (or has) the part objects, but the part objects can survive or exist without the enclosing (or whole) object. – Example: Library - Book A Library can have many Books, while a Book cannot belong to many Libraries (there is an ownership), but both have their own lifecycles (both can be created and deleted independently) → so when a Library shuts down, its Books do not disappear and can be transferred to other Library. Aggregation in Concept Aggregation is a special form of association. Aggregation refers to a has-a relationship between two objects (whole/part). – The objects have an independent lifecycle, but there is an ownership between the objects where the whole object contains (or has) the part objects, but the part objects can survive or exist without the enclosing (or whole) object. – Example: Library - Book A Library can have many Books, while a Book cannot belong to many Libraries (there is an ownership), but both have their own lifecycles (both can be created and deleted independently) → so when a Library shuts down, its Books do not disappear and can be transferred to other Library. Aggregation in Concept Aggregation is a special form of association. Aggregation refers to a has-a relationship between two objects (whole/part). – The objects have an independent lifecycle, but there is an ownership between the objects where the whole object contains (or has) the part objects, but the part objects can survive or exist without the enclosing (or whole) object. – Example: Library - Book A Library can have many Books, while a Book cannot belong to many Libraries (there is an ownership), but both have their own lifecycles (both can be created and deleted independently) → so when a Library shuts down, its Books do not disappear and can be transferred to other Library. A Library has many Books. * *open diamond represents the whole object Composition in Concept Composition is a special form of aggregation. Composition refers to a part-of relationship between two objects (whole/part). – The part object’s lifecycle is dependent on the whole object, where the part object is created by the whole object and is destroyed when the whole object is destroyed. – Example: Building - Room A Building can have many Rooms, while a Room cannot belong to many Buildings (there is an ownership), and a Room’s lifecycle is dependent on its Building → a Room cannot exist without a Building and when a Building is destroyed, its Rooms will no longer exist. Composition in Concept Composition is a special form of aggregation. Composition refers to a part-of relationship between two objects (whole/part). – The part object’s lifecycle is dependent on the whole object, where the part object is created by the whole object and is destroyed when the whole object is destroyed. – Example: Building - Room A Building can have many Rooms, while a Room cannot belong to many Buildings (there is an ownership), and a Room’s lifecycle is dependent on its Building → a Room cannot exist without a Building and when a Building is destroyed, its Rooms will no longer exist. Composition in Concept Composition is a special form of aggregation. Composition refers to a part-of relationship between two objects (whole/part). – The part object’s lifecycle is dependent on the whole object, where the part object is created by the whole object and is destroyed when the whole object is destroyed. – Example: Building - Room A Building can have many Rooms, while a Room cannot belong to many Buildings (there is an ownership), and a Room’s lifecycle is dependent on its Building → a Room cannot exist without a Building and when a Building is destroyed, its Rooms will no longer exist. A Building has many Rooms. * *filled black diamond represent the whole object Association, Aggregation and Composition Both Composition and Aggregation are Association. Aggregation is a weak association. Composition is a strong association. Implementation of Association in Java class Book { String title; ArrayList authorList = new ArrayList(); public Book(String t, ArrayList authors) { title = t; authorList = authors; Author objects are not } created by Book } class Author { ArrayList bookList = new ArrayList(); public void addNewBook(Book newBook) { bookList.add(newBook); } Book objects are not } created by Author Implementation of Aggregation in Java * class Book { String title;... } class Library { ArrayList bookList = new ArrayList(); public void addNewBook(Book newBook) { bookList.add(newBook); } Book objects are not created by } Library, although Book objects are part of Library There is not much difference between code for: class Book { String title; ArrayList authorList = new ArrayList(); public Book(String t, ArrayList authors) { title = t; authorList = authors; } } * class Library { ArrayList bookList = new ArrayList(); public void addNewBook(Book newBook) { bookList.add(newBook); } } So, this: is normally used to represent this: class Library { ArrayList bookList = new ArrayList(); public void addNewBook(Book newBook) { bookList.add(newBook); } } Implementation of Composition in Java * class Room {... } class Building { ArrayList rooms = new ArrayList(); public Building() { Room objects are created by Room room1 = new Room(); Building, so if this object of Room room2 = new Room(); Building is deleted, the two Room rooms.add(room1); objects created here are deleted rooms.add(room2); too } } Inheritance in Concepts Inheritance refers to a is-a relationship between two objects (parent/child). – The child object inherits general data and behaviours from the parent object, and has its own special data or behaviours. – Example: Member - VIPMember A Member can borrow books from the library. A VIP Member is a special kind of Member, who can borrow books from the library and reserve a book. Inheritance in Concepts Inheritance refers to a is-a relationship between two objects (parent/child). – The child object inherits general data and behaviours from the parent object, and has its own special data or behaviours. – Example: Member - VIPMember A Member can borrow books from the library. A VIP Member is a special kind of Member, who can borrow books from the library and reserve a book. Inheritance in Concepts Inheritance refers to a is-a relationship between two objects (parent/child). – The child object inherits general data and behaviours from the parent object, and has its own special data or behaviours. – Example: Member - VIPMember A Member can borrow books from the library. A VIP Member is a special kind of Member, who can borrow books from the library and reserve a book. A Member can borrow books from the library. A VIP Member is a special kind of Member, who can borrow books from the library and reserve a book. (Inheritance) Is-A vs. (Association) Has-A In simple term: – "is a" represent the inheritance/extends – "has a" represents the association/aggregation/composition For example: – House is a Building (inheritance) – House has a Door (association) Duplicate Code and Inheritance/Association In the beginning... there were no inheritance and no association, only code. And the code was repetitive. Copy and Paste were the primary mechanisms of code reuse. move openDoor stop closeDoor stop move openDoor closeDoor stop move no inheritance and no association only copy and paste hence, duplicate code Association and inheritance allow existing code to be reused by defining new class to abstract the duplicate code → parent class in inheritance, and part class in association. class Vehicle { void move() {... } void stop() {... } } class Door { void open() {... } void close() {... } } class Car extends Vehicle { Door door; public Car() { association: composition! door = new Door(); // Car has only one Door! } void openDoor() { door.open(); } void closeDoor() { door.close(); } // other method exclusive for Car } class Bicycle extends Vehicle {} class Boat extends Vehicle { Door door; public Boat() { association: composition! door = new Door(); // Boat has only one Door! } void openDoor() { door.open(); } void closeDoor() { door.close(); } // other method exclusive for Boat } When to Use Inheritance and Association Use Inheritance when: – A class needs to use property and behaviour of another class, and the two classes logically belong to the same category. – E.g. Book – PrintedBook, eBook Use Association when: – A class needs to use property and behaviour of another class, without modifying the code, and the two classes do not logically belong to the same category. – E.g. Book and Chapter (Book contains Chapter) Inheritance in Java - Abstract Class Inheritance Inheritance is a feature of OOP that allows code to be reused. Instead of always creating a completely new class to capture specific type, you can define a class that is based on an existing class. – Generally, the subclass provides additional methods that are specific to its needs or that alter the behaviour of existing methods in the superclass (i.e. method overriding). Inheritance Inheritance is a feature of OOP that allows code to be reused. Instead of always creating a completely new class to capture specific type, you can define a class that is based on an existing class. – Generally, the subclass provides additional methods that are specific to its needs or that alter the behaviour of existing methods in the superclass (i.e. method overriding). Abstract Class in Inheritance Often, the superclass does not have a "meaning" or does not directly relate to an object in the real world. Animal Abstract object type (UML: name is italic) Abstract class can be used to model abstract concepts in real world. public abstract class Animal {...} The class cannot be instantiated directly. new Animal(); // Compilation error! Therefore, an abstract class must be implemented by a subclass. public class Cat extends Animal {...} → new Cat(); // OK Abstract class can be used to model abstract concepts in real world. public abstract class Animal {...} The class cannot be instantiated directly. new Animal(); // Compilation error! Therefore, an abstract class must be implemented by a subclass. public class Cat extends Animal {...} → new Cat(); // OK Abstract class can be used to model abstract concepts in real world. public abstract class Animal {...} The class cannot be instantiated directly. new Animal(); // Compilation error! Therefore, an abstract class must be implemented by a subclass. public class Cat extends Animal {...} → new Cat(); // OK Other than common members, such as variables and methods, an abstract class can contain abstract methods. Abstract method: Provides no method body. Designed to be overriden by subclass(es) of the abstract class. Why we need an abstract method? Other than common members, such as variables and methods, an abstract class can contain abstract methods. Abstract method: Provides no method body. Designed to be overriden by subclass(es) of the abstract class. Why do we need an abstract method? Implementation of inheritance without abstract class: public class Animal { protected String type; public Animal() { type = "Animal"; } public Animal(String type) { this.type = type; } public void makeSound() { System.out.println("Animal can make sound"); } } public class Cat extends Animal { public Cat() { super("Cat"); } public void makeSound() { System.out.println(type + ": meow meow.."); } } public class Dog extends Animal { Overriding method public Dog() { makeSound in superclass super("Dog"); } public void makeSound() { System.out.println(type + ": woof! woof!"); } } public class TestAllAnimals { public static void main(String[] args { Animal[] animals = new Animal; animals = new Animal(); animals = new Cat(); animals = new Dog(); for (int i=0; i