AC-S24-OOP-Lect03-Part2-Polymorphism.pdf

Full Transcript

Lect 03A CST8132 OOP Algonquin College Lect 03B Computer Engineering Technology CST8132 OOP Summer, 2024 Based on resources developed by prof....

Lect 03A CST8132 OOP Algonquin College Lect 03B Computer Engineering Technology CST8132 OOP Summer, 2024 Based on resources developed by prof. Howard Rosemblum, James Mwangi, Anu Thomas and Ramanjeet Singh. Prof. Paulo Sousa Algonquin College Lect 03B Computer Engineering Technology Polymorphism CST8132 OOP Summer, 2024 Based on resources developed by prof. Howard Rosemblum, James Mwangi, Anu Thomas and Ramanjeet Singh. Prof. Paulo Sousa L1 L2 Week 3B: Polymorphism A2W01 A2W02 A2W09 A2W10 A2W03 A2W11 A2W04 A2W12 A2W05 A2W13 Basic concepts A2W06 A2W14 Examples A2W07 A2W15 A2W08 4 OOP – Week 3 Basic Concepts 5 Objectives Features of OO Encapsulation Polymorphism Abstraction Inheritance Package 6 Objects, Attributes, and Behaviors of Objects Procedural Concepts programming Write methods or Object: procedures that perform An entity in real-life with distinct states operations on data. (attributes) and behaviors (methods). (focus of CST8116) Examples of real world Objects: student, Object Oriented patient, librarian, rectangle, invoice, account Programming Has a unique identity, state, and behavior. Writing reusable programs using objects that encapsulate data and methods. (Focus of CST8132) 5 7 Today’s Topics Lab 2 – College System I Objects Attributes and Behaviors of Objects Relationships between Objects Features of OOP Encapsulation Polymorphism Abstraction Inheritance Lab 3 – College System II 8 Objects Objects are specified by Classes Objects have: State (properties or attributes or instance variables or fields) Behavior (methods) 9 Object State Object state is given by the instance variables Instance variables are declared at the top of the class outside of any method Variables declared inside a method are called local variables they exist only when the method is running Instance variables can be primitive variables or reference variables Primitive: the variable contains the actual value int num = 10; Reference Employee emp = new Employee(); 10 Instance Variables vs Local Variables Local variables Declared INSIDE a block (method, for-loop, if statement etc.) These are TEMPORARY variables used for programming purposes These exist only when the block is running Every time the block runs, the variable is born again (no old values) These do not represent the state of the object Instance variables Declared OUTSIDE methods in the class body Come into existence when the object is instantiated (with new keyword) Together these represent the state of the object 11 Common Mistake (instance vs local) Hiding an instance variable with an accidental local variable declaration public class Lecture2 { private int x; public void doit(int val) { int x = val; } public void printIt(){ System.out.println("x : " + x); } public static void main(String[] args) { Lecture2 lec = new Lecture2(); lec.doit(5); lec.printIt(); } } 12 Methods In OOP, we set up object(s) and start the processing by using (one of) the object(s) to call one of its methods We do two different things with a method Define a method public class Lecture2 { public int add(int x, int y) { return x+y; } } Invoke a method Lecture2 lec = new Lecture2(); int sum = lec.add(3, 4); 13 Method Signature A method signature is the method’s name and the list of its parameter types These methods all have the same signature: public void doIt(int x, int y, Account acc1){...}; public int doIt(int i, int j, Account acc2){...}; public Account doIt(int x, int y, Account acc3){...}; 14 Method Signature In other words, all of these are methods named doIt that takes two ints and an Account as parameters. Return types and thrown exceptions are not considered to be a part of the method signature 15 Topics for discussion Account Instance variable: name (String) Setter Getter Why this is required in this example? Return values of methods Private vs public Driver class : Lecture2 Scanner for receiving user input Instantiating an object – acc default constructor calling setters and getters UML top compartment – class name middle compartment – Attributes bottom compartment – methods +/- – access modifiers (- for private) 16 Topics for discussion Account Constructor Syntax Any return value for constructors? default constructors Driver class : Lecture2 How constructor gets invoked? At this time, can it be possible to have a statement Account acc3 = new Account(); 17 Objectives Features of OO Encapsulation Polymorphism Abstraction Inheritance Package 18 Encapsulation Process of hiding details of an object from other objects So programmers can’t do unexpected things to data inside the object Provides a way of defining a portable application Leads to APIs Reusability Leads to abstraction & encourages modularity easier maintenance 19 How can encapsulation help? Every object has control over member functions/data It will be specified which member is accessible and which is not Members that are only created for internal use of the object are hidden from outsiders Well-intended outsiders won’t make unwanted mistakes Evil-intended outsiders have more difficulty hacking the code 20 Abstraction Process of finding commonalities between different objects Results in hierarchy of superclass-subclass Inheritance Also, defining an abstract behavior to represent common behavior of subclasses Subclasses may implement the behavior in different ways Polymorphism 21 How can abstraction help? You’re about to develop an application to help users throughout their stock management Users have different preferences Communication medium, investment rules, etc Conventional programming Build a specific application for each system You have to create separate information packages for customers and developers for every new system 22 How can abstraction help? OOP Create abstract classes that represent the common features Inherit from common features and create specific classes 23 Examples of Objects 1. Student 2. Professor 1. Student 1. Professor Number Number 2. Name 2. Name 3. Address 3. Address 4. Telephone 4. Telephone 24 Example Student and Professor share attributes A new design: Person Name Address Telephone Student and Professor inherit from Person Person is called the super-class Student & Professor are called sub-classes 25 Inheritance When we are writing our classes, we can use an existing class as a starting point Suppose we have a Person class, and we want to add a Student class that is based on Person We would say Student is-a Person Student is a new class based on Person Student will inherit the attributes and methods of Person More Student-specific attributes and methods can be added Example: public class Student extends Person 26 Inheritance (cont’d) With inheritance, we can create new classes from existing classes extends keyword: public class B extends A A is the superclass B is the subclass 27 Inheritance (cont’d) B inherits all of the members of A The members are fields and methods The constructors of the superclass is invoked by the subclass constructors Private members of A are not visible in B B can add new fields and members B can override methods of A If a method in A named doIt() is overridden in B, then in B, doIt() invokes the B version, and super.doIt() invokes the A version. 28 Access Modifiers Private Only instances of the class itself can access it Protected Only instances of the class and instances of the subclasses can access Package (default) Members of the same package can access all members Public Everyone has access. can be accessed from within the class, outside the class, within the package and outside the package 29 Access modifiers (contd.) Access Java UML symbol Within class Within Is subclass Not subclass Modifier keyword package Public public + Y Y Y Y Protected protected # Y Y Y N Package ~ Y Y N N Private private - Y N N N 30 Java Constructors and Inheritance If no constructor is defined for a class, a default constructor is implicit. The default constructor for the super-class is automatically implicitly called by the constructor of a sub- class (unless at the beginning, super is called explicitly) If any non-default constructor is defined, there is no implicit default constructor which can cause compile time errors when a subclass needs the superclass to have a default constructor this() can be used in a constructor to refer to another constructor of the current class. public Square(){ Ex: a constructor Square() referring to this(4); Square(int sideLength) as in: } Note: if the sideLength is not specified, a sideLength of 4 is used 31 Inheritance and Overriding methods When one class extends another class, in the subclass, the programmer can override a method with the same signature in the superclass We use the @Override annotation on the method in the subclass The subclass version of the method will be the version used by the objects of the subclass If we want to use the superclass version, we can use super.methodName(); 32 static keyword Discussion of static versus instance Static variables and static methods are a part of the class itself All objects of the class, if any, use the SAME copy of them Static variables and methods can be used BEFORE any objects of that class are instantiated Static members should be referenced by the ClassName itself Example of using static method “sort” ofArrays class: Arrays.sort(myArray) (reference forArrays class: https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html) Instance members do not exist until an object has been created (with the new keyword) Instance members are accessed through a reference to the object 33 Inheritance and Polymorphism Shapes Example A circle “is-a” shape A triangle “is-a” shape We will make shape a parent class Demonstration of calculating areas of different shapes Ex: Bicycles example of polymorphism http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html 34 Lab3 – College System II Create different classes and think about their relationships Activity 35 Open questions… Any doubts / questions? How we are until now? 36 See you… Enjoy our course and season… 37 OOP – Week 2 Thank you for your attention! Contact: [email protected] 38

Use Quizgecko on...
Browser
Browser