CSEN401 Computer Programming Lab. Topics: Object Oriented Features: Abstraction and Polymorphism

Similar documents
Polymorphism. Polymorphism is an object-oriented concept that allows us to create versatile software designs

CS Week 14 Page 1

Inheritance. Transitivity

First IS-A Relationship: Inheritance

What is Inheritance?

More Relationships Between Classes

Chapter 5. Inheritance

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Introduction to Object-Oriented Programming

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Object Orientated Programming Details COMP360

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance (Outsource: )

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

CS Week 15 Page 1

Create a Java project named week10

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance -- Introduction

Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Example: Count of Points

CS-202 Introduction to Object Oriented Programming

Exercise: Singleton 1

Chapter 5 Object-Oriented Programming

Java Fundamentals (II)

OVERRIDING. 7/11/2015 Budditha Hettige 82

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Practice for Chapter 11

3. Can an abstract class include both abstract methods and non-abstract methods? D

ITI Introduction to Computing II

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

C++ Important Questions with Answers

ECE 122. Engineering Problem Solving with Java

Object Oriented Programming. Java-Lecture 11 Polymorphism

Example: Count of Points

COMP 110/L Lecture 19. Kyle Dewey

ITI Introduction to Computing II

Binghamton University. CS-140 Fall Dynamic Types

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Instance Members and Static Members

1 Shyam sir JAVA Notes

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance and Polymorphism

Inheritance and Polymorphism

Java Magistère BFA

CT 229 Object-Oriented Programming Continued

QUESTIONS FOR AVERAGE BLOOMERS

Create a Java project named week9

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Starting Out with Java: From Control Structures Through Objects Sixth Edition

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

Object-Oriented Concepts and Principles (Adapted from Dr. Osman Balci)

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Object Oriented Concepts. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Class, Variable, Constructor, Object, Method Questions

Subtype Polymorphism

Static and Dynamic Behavior לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

EKT472: Object Oriented Programming. Overloading and Overriding Method

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

COP 3330 Final Exam Review

Introduction to Programming Using Java (98-388)

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Full file at Chapter 2 - Inheritance and Exception Handling

Chapter 9 Inheritance

Inheritance, polymorphism, interfaces

Java Object Oriented Design. CSC207 Fall 2014

Informatik II (D-ITET) Tutorial 6

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Concepts of Programming Languages

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Object-Oriented Programming More Inheritance

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Multiple Inheritance, Abstract Classes, Interfaces

Sorting. Sorting. Selection sort

What are the characteristics of Object Oriented programming language?

Classes, Objects, and OOP in Java. June 16, 2017

Interface Class. Lecture 22. Based on Slides of Dr. Norazah Yusof

CS260 Intro to Java & Android 03.Java Language Basics

Transcription:

CSEN401 Computer Programming Lab Topics: Object Oriented Features: Abstraction and Polymorphism Prof. Dr. Slim Abdennadher 23.2.2015 c S. Abdennadher 1

Object-Oriented Paradigm: Features Easily remembered as A-PIE Abstraction Polymorphism Inheritance Encapsulation c S. Abdennadher 2

Abstraction Data abstraction: The process of refining away the unimportant details of an object, so that only the useful characteristics that define it remain. c S. Abdennadher 3

Abstract Classes Abstract classes are classes that represent an Abstract Concept. Creating an Object from the class makes no sense. Example: Greeting cards An abstract class cannot be instantiated. c S. Abdennadher 4

Abstract Classes Example (I) The parent class is Card. abstract class Card {... // definitions of methods and variables Children classes are Valentine, Holiday, and Birthday. class Holiday extends Card {... c S. Abdennadher 5

Abstract Classes Example (II) An object must be an instance of one of the three child types: Valentine, Holiday, and Birthday. There will be no such thing as an object that is merely a Card. The purpose of an abstract class is to be a parent to several related classes. The child classes inherit from the abstract parent class. c S. Abdennadher 6

Abstract Methods Example A card object will have a greeting() method that writes out a greeting. Each type of card contains an appropriate greeting: The Holiday card says Season s Greetings. The Birthday card says Happy Birthday. The Valentine card says Love and Kisses. Class definition of the abstract class Card abstract class Card { String recipient; public abstract void greeting(); // name of who gets the card // abstract greeting() method An abstract method has no body, i.e. it has no statements. An abstract method declares an access modifier, return type, and method signature followed by a semicolon. c S. Abdennadher 7

Abstract and Non-Abstract Methods A non-abstract child class inherits the abstract method and must define a non-abstract method that matches the abstract method. class Holiday extends Card { public void greeting() { System.out.println("Dear " + recipient + ",\n"); System.out.println("Season s Greetings!\n\n"); An abstract class can contain non-abstract methods, which will be inherited by the children. An abstract child of an abstract parent does not have to define non-abstract methods for the abstract signatures it inherits. If a class contains even one abstract method, then the class itself has to be declared to be abstract. c S. Abdennadher 8

Advantage of Abstract Classes The advantage of using an abstract class is that you can group several related classes together as siblings. Grouping classes together is important in keeping a program organized and understandable. You can get the same thing done without using this way to organize. This is a matter of program design, which is not easy at all. c S. Abdennadher 9

Abstraction and the Programmer The task of the programmer, given a problem, is to determine what data needs to be extracted (i.e. abstracted) in order to adequately design and ultimately code a solution. Normally, with a good problem description and/or good customer communication this process is relatively painless. It is difficult to precisely describe how a programmer can determine which data items are important. In part it involves having a clear understanding of the problem. Equally, it involves being able to see ahead to how the problem might be modeled/solved. Given such understanding, it is normally possible to determine which data items will be needed to model the problem. However, please note, the ability to abstract relevant data is a skill that is largely not taught, but rather one that is refined through experience. c S. Abdennadher 10

Problems with Abstraction Two possible forms: Something unnecessary was abstracted, i.e. some data is redundant. This may or may not be a problem, but it is bad design. Something needed was not abstracted. This is a more serious problem, usually discovered later in the design or coding stages, and entails that the design needs to be changed to incorporate the missing data item, code changed, etc. c S. Abdennadher 11

Interface for Stacks public interface Stack { public boolean isempty(); public boolean isfull(); public Object peek(); public Object pop(); public void push(object item); public int size(); c S. Abdennadher 12

Interfaces An interface contains method declarations. All methods declared in an interface are implicitly public, so the public modifier can be omitted. An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. A class can implement more than one interface. This class should implement all methods declared in the interfaces. It is possible, however, to define a class that does not implement all of the interface methods, provided that the class is declared to be abstract. An interface cannot be instantiated. However, you can use an interface as a type. c S. Abdennadher 13

Interfaces versus Abstract Classes An abstract class is an incomplete class that requires further specification (before instances of that class can exist). An interface is solely a specification or prescription of behavior. An interface does not have any suggestion of a hierarchical relationship that is central to inheritance. A class can implement several different interfaces, however it can only inherit from one class (single inheritance). Interfaces should be used to capture similarities between unrelated classes without artificially enforcing a class relationship. c S. Abdennadher 14

Polymorphism c S. Abdennadher 15

Polymorphism Polymorphism comes from a Greek word meaning many forms. Two types of polymorphism: Static Polymorphism Dynamic Polymorphism c S. Abdennadher 16

Static Polymorphism In Java, a class can have multiple methods with the same name. When two or more methods in a class have the same name, the method is said overloaded. The methods must be different somehow, or else the compiler would not associate a call to a particular method definition. c S. Abdennadher 17

Method Signature The compiler identifies a method by more than its name. A method is uniquely identified by its signature. A method signature consists of the method s name and its parameter list If the parameter types do not match exactly, both in number and position, then the method signatures are different. Example: System.out.println(int) System.out.println(String) -- prints number -- prints text c S. Abdennadher 18

Example Overloading 1. static void f() {/*... */ This version has no parameters, so its signature differs from all the others which each have at least one parameter. 2. static void f(int x) {/*... */ This version differs from version 3, since its single parameter is an int, not a double. 3. static void f(double x) {/*... */ This version differs from version 2, since its single parameter is a double, not an int. 4. static void f(int x, double y) {/*... */ This version differs form version 5 because, even though versions 4 and 5 have the same number of parameters with the same types, the order of the types is different. 5. static void f(double x, int y) {/*... */ c S. Abdennadher 19

Dynamic Polymorphism Late Binding class Human { public String getgender() {return "Neutral"; class Man extends Human { public String getgender() {return "Man"; class Woman extends Human { public String getgender() {return "Woman"; c S. Abdennadher 20

Overriding What is the output of the following code? Human human = new Human(); System.out.println("Gender: " + human.getgender()); Man man = new Man(); System.out.println("Gender: " + man.getgender()); Woman woman = new Woman(); System.out.println("Gender: " + woman.getgender()); Neutral Man Woman c S. Abdennadher 21

Dynamic Binding What is the output of the following code? Human human = new Human(); System.out.println("Gender: " + human.getgender()); Human man = new Man(); System.out.println("Gender: " + man.getgender()); Neutral Man The method that got invoked, is the version that is present in the object type and NOT the reference type. c S. Abdennadher 22

Dynamic Binding Example Assume that three subclasses (Cow, Dog and Snake) have been created based on the Animal super class, each having their own speak() method. public class AnimalReference { public static void main(string args[]) Animal ref // set up var for an Animal Cow acow = new Cow("Bossy"); // makes specific objects Dog adog = new Dog("Rover"); Snake asnake = new Snake("Earnie"); // now reference each as an Animal ref = acow; ref.speak(); ref = adog; ref.speak(); ref = asnake; ref.speak(); No Animal object exists. The program is able to resolve the correct method related to the subclass object at runtime. c S. Abdennadher 23

Downcasting and instanceof class Animal { //... class Dog extends Animal { public void woof() { System.out.println("Woof!"); //... class Cat extends Animal { public void meow() { System.out.println("Meow!"); //... class Hippopotamus extends Animal { c S. Abdennadher 24

Downcasting and instanceof public void roar() { System.out.println("Roar!"); //... c S. Abdennadher 25

Downcasting and instanceof class Example { public static void main(string[] args) { makeittalk(new Cat()); makeittalk(new Dog()); makeittalk(new Hippopotamus()); public static void makeittalk(animal animal) { if (animal instanceof Cat) { Cat cat = (Cat) animal; cat.meow(); else if (animal instanceof Dog) { Dog dog = (Dog) animal; dog.woof(); else if (animal instanceof Hippopotamus) { c S. Abdennadher 26

Downcasting and instanceof Hippopotamus hippopotamus = (Hippopotamus) animal; hippopotamus.roar(); c S. Abdennadher 27

abstract class Animal { public abstract void talk(); //... The OO Way class Dog extends Animal { public void talk() { System.out.println("Woof!"); //... class Cat extends Animal { public void talk() { System.out.println("Meow!"); c S. Abdennadher 28

The OO Way //... class Hippopotamus extends Animal { public void talk() { System.out.println("Roar!"); //... class Example2 { public static void main(string[] args) { makeittalk(new Cat()); makeittalk(new Dog()); makeittalk(new Hippopotamus()); c S. Abdennadher 29

The OO Way public static void makeittalk(animal animal) { animal.talk(); c S. Abdennadher 30

Static Polymorphism versus Dynamic polymorphism Static polymorphism is associated with overloaded methods because it gives the impression that a single named method will accept a number of different argument types, e.g. System.out.println method. Each overloaded method is separate and the compiler can see the difference between them at compile time. Dynamic polymorphism is where a class overrides a superclass method. Any differences in the methods implementations are only seen at runtime, so they are considered dynamic. c S. Abdennadher 31