CSA 1019 Imperative and OO Programming

Size: px
Start display at page:

Download "CSA 1019 Imperative and OO Programming"

Transcription

1 CSA 1019 Imperative and OO Programming Object Oriented III Mr. Charlie Abela Dept. of of Artificial Intelligence

2 Objectives Getting familiar with Method Overriding Polymorphism Overriding Vs Vs Overloading Dynamic binding UpCasting and and DownCasting objects instanceof operator ArrayList and Vector Charlie Abela CSA1019: OOP III 2

3 Method Overriding Reconsider the the geometry hierarchy. The The method tostring() is is defined in in the the Shape class class and and overridden in in both both the the Rectangle and and the the Circle classes. Shape -colour:string = "white" -datecreated: java.util.date + Shape() +setcolour(col: String): void +getcolour(): String +getdatecreated():java.util.date +tostring():string Rectangle Circle -width:double = 1.0 -length:double = 1.0 +Rectangle() +Rectangle(w:double, l:double) +setwidth(w:double):void +getwidth():double +setlength(l:double):void +getlength():double +tostring():string +calculatearea():double -radius:double = 1.0 +Circle() +Circle(r:double) +setradius(r:double):void +getradius():double +tostring():string +calculatearea():double Charlie Abela CSA1019: OOP III 3

4 Method Overriding (cont) Method overriding involves the creation of of another method (in a subclass) which has the same signature, and its return type is is compatible with that of of the method in in the superclass. public class class Shape{ public String tostring(){ return This This is is a Shape Shape object ; public class class Square extends Shape{ public String tostring(){ return This This is is a Square object ; Charlie Abela CSA1019: OOP III 4

5 Method Overriding (cont) It It is is not possible to to override a method which is is marked as as final or or as as static The access level cannot be more restrictive than that of of the overridden method s. However it it can be less. In In essence, if if a method cannot be inherited for some reason, then it it cannot be overridden. Charlie Abela CSA1019: OOP III 5

6 Method Overriding (cont) Implementation of of tostring in in the Shape class public String tostring(){ return getcolour()+ shape created on on +getdatecreated(); Implementation of of tostring in in the Circle class public String tostring(){ return getcolour()+ Circle created on on +getdatecreated(); Therefore this is is possible Shape s = new new Shape(); Circle c = new new Circle(); s.tostring(); //invoke the the overriden version c.tostring(); Charlie Abela CSA1019: OOP III 6

7 Better use of overriding Re-implementation of of the tostring in in the Shape class public String tostring(){ return Colour: +getcolour()+ \n \n DateCreated: +getdatecreated(); Re-implementation of of the tostring in in the Circle class public String tostring(){ return Circle Details \n + \n + super.tostring(); In In this way the parent s tostring method is is reused in in an effective manner Charlie Abela CSA1019: OOP III 7

8 Overriding Vs Overloading public class class Test{ Test{ public static void void main(string[] args){ A a = new new A(); A(); a.p(10); public class class B{ B{ public void void p(int p(int i){ i){ System.out.println( B prints +i); +i); public class class A extends B{ B{ public void void p(int p(int i){ i){ System.out.println( A prints +i); +i); A prints Charlie Abela CSA1019: OOP III 8

9 Overriding Vs Overloading public class class Test{ Test{ public static void void main(string[] args){ A a = new new A(); A(); a.p(10); public class class B{ B{ public void void p(int p(int i){ i){ System.out.println( B prints +i); +i); public class class A extends B{ B{ public void void p(double i){ i){ System.out.println( A prints +i); +i); B prints Charlie Abela CSA1019: OOP III 9

10 Binding Consider the the following method invocation: obj.doit(); At At some point, this invocation is is bound to to the the definition of of the the method that it it invokes If If this binding occurred at at compilation time, then that line of of code would call the the same method every time However, Java defers method binding until run time this is is called dynamic binding or or late binding Late binding provides flexibility in in program design Charlie Abela CSA1019: OOP III 10

11 Polymorphism Means many forms It It is is the the ability to to treat an an object of of any subclass as as if if it it were an an object of of the the base/super class. A base class will therefore have many forms as as itself itself as as any any of of its its subclasses Polymorphism makes effective use of of dynamic binding or or late late binding Why is is polymorphism important? allows for for improved code code organisation and and readability for for creating extensible programs (generic programming): programs that that grow in in time time with with little little effect on on existing code code Charlie Abela CSA1019: OOP III 11

12 Example Shape Circle Rectangle Shape s = new new Shape(); through polymorphism the the following is is also possible Shape s1 s1 = new new Circle(); Shape s2 s2 = new new Rectangle(); This is is called upcasting (i.e. going from a subclass up, towards a superclass) Upcasting is is always possible since a subclass can always behave like its its superclass. Charlie Abela CSA1019: OOP III 12

13 Example (cont) Therefore this is is also possible Shape s1 s1 = new new Circle(); Shape s2 s2 = new new Rectangle(); s1.tostring(); s2.tostring(); s1.tostring() will invoke the Circle s tostring() method Circle Details Colour: white white DateCreated: 12/12/07 s2.tostring() will invoke the Rectangle s tostring() method Rectangle Details Colour: white white DateCreated: 12/12/07 Charlie Abela CSA1019: OOP III 13

14 Dynamic Binding The compiler checks the declared reference types at at compilation time, however the JVM checks the real object at at runtime. When the tostring method is is called via the Shape reference variable: the the JVM looks at at the the real objects at at the the other end of of the the reference, sees that the the method has been overridden by by both the the Circle and Rectangle classes and invokes the the method in in the the object s class. This is is also referred to to as as virtual method invocation Charlie Abela CSA1019: OOP III 14

15 Dynamic Binding II Dynamic binding works as as follows: Suppose an object o is is an instance of of classes C 1,, C 2,,..., C n-1 n-1,, and C n,, where C 1 is is a subclass of of C 2,, C 2 is is a subclass of of C 3,,..., and C n-1 n-1 is is a subclass of of C n.. C n is n is the the most general class C 1 is 1 is the the most specific class. In In Java, C n is n is the the Object class. If If o invokes a method p, p, the the JVM searches the the implementation for for the the method p in in C 1, 1, C 2, 2,..., C n-1 and n-1 C n, n, in in this order, until it it is is found. Once an an implementation is is found, the the search stops and the the first-found implementation is is invoked. Charlie Abela CSA1019: OOP III 15

16 Dynamic Binding III C n Object C n-1... C 2 C 1 Since o is an instance of C 1, o is also an instance of C 2, C 3,...C n -1 and C n. Charlie Abela CSA1019: OOP III 16

17 Polymorphism in Animals Animal Lion Cat Horse Wolf Dog Animal[] animals = new new Animal[5]; animals[0] = new new Dog(); animals[1] = new new Cat(); animals[2] = new new Wolf(); animals[3] = new new Horse(); animals[4] = new new Lion(); for(int i = 0; 0; i < animals.length; i++){ i++){ animals[i].eat(); Each Each object in in the the array array is is referenced by by a more more generic reference variable At At runtime, however, the the actual object is is seen seen by by the the JVM, and and the the appropriate object s eat eat method is is invoked. Charlie Abela CSA1019: OOP III 17

18 Polymorphic Arguments What happens in in this code? public class class Vet{ Vet{ public void void giveshot(animal a){ a){ //assume all all animals have have this this method a.makenoise(); public class class PetOwner{ public void void taketovet(){ Vet Vet v = new new Vet(); Dog Dog d = new new Dog(): Horse Horse h = new new Horse(); v.giveshot(d); v.giveshot(h); Dog s Dog s makenoise() invoked Horse s makenoise() invoked Charlie Abela CSA1019: OOP III 18

19 Polymorphic Arguments II What is is the output of of this code? public class class Animal{ public class class Horse Horse extends Animal{ public class class UseAnimals{ public void void dostuff(animal a){ a){ System.out.println( Animal version ); public void void dostuff(horse h){ h){ System.out.println( Horse version ); public static void void main(string[] args){ UseAnimals ua ua = new new UseAnimals(); Animal animalobj = new new Animal(); Horse Horse horseobj = new new Horse(); ua.dostuff(animalobj); ua.dostuff(horseobj); Animal version Horse Horse version Charlie Abela CSA1019: OOP III 19

20 Polymorphic Arguments II (cont) What if if an Animal reference is is assigned to to a Horse object? Animal animalref = new new Horse(); ua.dostuff(animalref); Which overloaded version is is invoked? Remember: Animal version The reference type determines which overloaded method is is invoked, at at compilation time The object type is is used to to determine which overridden version of of a method is is called at at runtime Charlie Abela CSA1019: OOP III 20

21 Overloaded and Overridden methods What happens when methods are both overloaded and overridden? public class class Animal{ public void void eat(){ System.out.println( Generic eating ); public class class Horse Horse extends Animal{ public void void eat(){ System.out.println( Horse eating hay ); public void void eat(string s){ s){ System.out.println( Horse eating + + s); s); Charlie Abela CSA1019: OOP III 21

22 Overloaded and Overridden methods II Method Invocation Animal a=new Animal(); a.eat(); Horse h = new Horse(); h.eat(); Animal ah= new Horse(); ah.eat(); Horse he= new Horse(); he.eat( apples ); Animal a2= new Animal(); a2.eat( treats ); Animal ah2= new Horse(); ah2.eat( Carrots ); Results Generic eating Horse eating hay Horse eating hay; due to polymorphism the actual object type is used to determine method Horse eating apples; overloaded eat(string s) method is invoked Compiler error! Compiler tries to find eat(string s) within Animal and fails Compiler error! Compiler still tries to find an eat(string s) in Animal and fails Charlie Abela CSA1019: OOP III 22

23 Downcasting In In the previous example the following code produced a compilation error Animal ah2= ah2= new new Horse(); ah2.eat( Carrots ); There is is however a solution Animal ah2= ah2= new new Horse(); ((Horse)ah2).eat( Carrots ); Downcast (explicit casting) the reference variable to to a Horse object and invoke its eat(string s) s) method. The compiler will not complain since he is is forced to to trust the developer Charlie Abela CSA1019: OOP III 23

24 Downcasting (cont) Explicit casting must be used when casting an object from a superclass to to a subclass. This type of of casting may not always succeed. Apple x = (Apple)fruit; Orange x = (Orange)fruit; Charlie Abela CSA1019: OOP III 24

25 Downcasting (cont) Downcasting could produce a ClassCastException if if not done correctly public class class Animal{ public class class Dog Dog extends Animal{ public class class DogTest{ public static void void main(string[] args){ Animal animal = new new Animal(); Dog Dog fido fido = (Dog)animal; Though this compiles, it it will fail at at runtime, giving an an exception, since we we are are trying to to downcast an an animal reference to to a Dog. However the the animal reference, was previously referring to to an an Animal object not a Dog object Charlie Abela CSA1019: OOP III 25

26 instanceof operator Use the instanceof operator to to check whether an object is is an instance of of a class or or not: Object myobject = new new Circle(); // // Some Some lines lines of of code code /** /** Perform casting if if myobject is is an an instance of of Circle */ */ if if (myobject instanceof Circle){ System.out.println("The circle diameter is is " + ((Circle)myObject).getDiameter()); Charlie Abela CSA1019: OOP III 26

27 static methods Static methods (and data fields) cannot be be overridden. However they can be be redefined in in a subclass. A redefined static method (in (in the the subclass), hides the the static method in in its its parent class public class class Animal{ public static void void dostuff(){ System.out.print( a ); public class class Dog Dog extends Animal{ public static void void dostuff(){ System.out.print( b ); public static void void main(string[] args){ Animal[] a={new Animal(), new new Dog(); for(int i=0; i=0; i < a.length; i++) i++) a[i].dostuff(); a a Charlie Abela CSA1019: OOP III 27

28 ArrayList & Vector The ArrayList and Vector classes implement dynamic arrays. The two classes are very similar except for some performancerelated features. Both classes allow for adding, removing and accessing elements. Declaring/Initialising Vectors and ArrayLists Vector v = new new Vector(); Vector v2 v2 = new new Vector(10); ArrayList a = new new ArrayList(2); ArrayList<String> a = new new ArrayList<String>(); Charlie Abela CSA1019: OOP III 28

29 Adding/Accessing elements import java.util.arraylist; ArrayList a = new new ArrayList(); a.add("string"); a.add(1); //possible due due to to AutoBoxing a.add(2.3); //possible due due to to AutoBoxing for(int i=0; i=0; i< i< a.size(); i++){ i++){ System.out.println(a.get(i).toString()); a.remove(1); System.out.println(a.size()); System.out.println(a.contains(2.3)); Charlie Abela CSA1019: OOP III 29

30 Adding/Accessing elements import java.util.arraylist; ArrayList clist clist = new new ArrayList(); clist.add(new Circle(3.4)); clist.add(new Circle(4.5)); clist.add(new Circle(2.3)); for(int i=0; i=0; i < clist.size(); i++){ i++){ System.out.println( Area of of circle: + ((Circle)clist.get(i)).getArea()); import java.util.arraylist; ArrayList<Cat> cats cats = new new ArrayList<Cat>(3); cats.add(new Lion("micio")); cats.add(new Cheetah("runner")); cats.add(new Tiger("grahhh")); for(int i=0; i=0; i < cats.size(); i++){ i++){ //no //no need need to to typecast System.out.println(cats.get(i).getName()); Charlie Abela CSA1019: OOP III 30

EKT472: Object Oriented Programming. Overloading and Overriding Method

EKT472: Object Oriented Programming. Overloading and Overriding Method EKT472: Object Oriented Programming Overloading and Overriding Method 2 Overriding Versus Overloading Do not confuse overriding a method in a derived class with overloading a method name When a method

More information

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

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles, Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism rights reserved. 2 Motivation Suppose you want to define classes to model circles, rectangles, and

More information

Chapter 11 Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism Chapter 11 Inheritance and Polymorphism 1 Motivations OOP is built on three principles: Encapsulation (classes/objects, discussed in chapters 9 and 10), Inheritance, and Polymorphism. Inheritance: Suppose

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR) Object Oriented Programming Part II of II Steve Ryder Session 8352 JSR Systems (JSR) sryder@jsrsys.com New Terms in this Section API Access Modifier Package Constructor 2 Polymorphism Three steps of object

More information

25. Generic Programming

25. Generic Programming 25. Generic Programming Java Fall 2009 Instructor: Dr. Masoud Yaghini Generic Programming Outline Polymorphism and Generic Programming Casting Objects and the instanceof Operator The protected Data and

More information

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini 24. Inheritance Java Fall 2009 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Superclasses and Subclasses Inheritance

More information

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Lecture Notes Chapter #9_b Inheritance & Polymorphism Lecture Notes Chapter #9_b Inheritance & Polymorphism Inheritance results from deriving new classes from existing classes Root Class all java classes are derived from the java.lang.object class GeometricObject1

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini 22. Inheritance Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Superclasses and Subclasses Using the super Keyword Overriding Methods The Object Class References Inheritance Object-oriented programming

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

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

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg

More information

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

IST311. Advanced Issues in OOP: Inheritance and Polymorphism IST311 Advanced Issues in OOP: Inheritance and Polymorphism IST311/602 Cleveland State University Prof. Victor Matos Adapted from: Introduction to Java Programming: Comprehensive Version, Eighth Edition

More information

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Inheritance & Polymorphism. Object-Oriented Programming

Inheritance & Polymorphism. Object-Oriented Programming Inheritance & Polymorphism Object-Oriented Programming Outline Example Design an inheritance structure IS-A and HAS-A Polymorphism protected access level Rules for overriding the Object class Readings:

More information

Object-Oriented ProgrammingInheritance & Polymorphism

Object-Oriented ProgrammingInheritance & Polymorphism Inheritance Polymorphism Overriding and Overloading Object-Oriented Programming Inheritance & Polymorphism Inf1 :: 2008/09 Inheritance Polymorphism Overriding and Overloading 1 Inheritance Flat Hierarchy

More information

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed 1 1 COMP200 INTERFACES OOP using Java, from slides by Shayan Javed Interfaces 2 ANIMAL picture food sleep() roam() makenoise() eat() 3 ANIMAL picture food sleep() roam() makenoise() eat() 4 roam() FELINE

More information

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Java Session. Day 2. Reference: Head First Java

Java Session. Day 2. Reference: Head First Java Java Session Day 2 shrishty_bcs11@nitc.ac.in Reference: Head First Java Encapsulation This hides the data!! How do we do it? By simply using public private access modifiers. 1. Mark the instance variables

More information

Object-Oriented Programming More Inheritance

Object-Oriented Programming More Inheritance Object-Oriented Programming More Inheritance Ewan Klein School of Informatics Inf1 :: 2009/10 Ewan Klein (School of Informatics) OOP: More Inheritance Inf1 :: 2009/10 1 / 45 1 Inheritance Flat Hierarchy

More information

Chapter 11 Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism Chapter 11 Inheritance and Polymorphism Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk 1 Motivations Suppose you will define classes

More information

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. Constructor Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design these classes so to avoid redundancy? The

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University Inheritance and Polymorphism CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Model classes with similar properties and methods: Circles, rectangles

More information

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9 Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract Classes Chapter

More information

Exercise: Singleton 1

Exercise: Singleton 1 Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance

More information

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College CISC 3115 TY3 C09a: Inheritance Hui Chen Department of Computer & Information Science CUNY Brooklyn College 9/20/2018 CUNY Brooklyn College 1 Outline Inheritance Superclass/supertype, subclass/subtype

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Polymorphism. Arizona State University 1

Polymorphism. Arizona State University 1 Polymorphism CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 15 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

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

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

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

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

CS1150 Principles of Computer Science Objects and Classes

CS1150 Principles of Computer Science Objects and Classes CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

Object-Oriented Programming

Object-Oriented Programming Abstract classes Object-Oriented Programming Outline Abstract classes Abstract methods Design pattern: Template method Dynamic & static binding Upcasting & Downcasting Readings: HFJ: Ch. 8. GT: Ch. 8.

More information

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Lecture 36: Cloning Last time: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting Today: 1. Project #7 assigned 2. equals reconsidered 3. Copying and cloning 4. Composition 11/27/2006

More information

Object-Oriented Programming

Object-Oriented Programming iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 40 Overview 1 2 3 4 5 2 / 40 Primary OOP features ion: separating an object s specification from its implementation. Encapsulation: grouping related

More information

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017 Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 11: Inheritance and Polymorphism Part 1 Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad

More information

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011

MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011 MORE OO FUNDAMENTALS CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 4 09/01/2011 1 Goals of the Lecture Continue a review of fundamental object-oriented concepts 2 Overview of OO Fundamentals

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Recitation 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class newsgroup. Make use of lab

More information

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012

More OO Fundamentals. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012 More OO Fundamentals CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 4 09/11/2012 1 Goals of the Lecture Continue a review of fundamental object-oriented concepts 2 Overview of OO Fundamentals

More information

Chapter 5. Inheritance

Chapter 5. Inheritance Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism through Method Overriding Learn the keywords : super

More information

Chapter 11 Inheritance and Polymorphism

Chapter 11 Inheritance and Polymorphism Chapter 11 Inheritance and Polymorphism rights reserved. 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

Inheritance -- Introduction

Inheritance -- Introduction Inheritance -- Introduction Another fundamental object-oriented technique is called inheritance, which, when used correctly, supports reuse and enhances software designs Chapter 8 focuses on: the concept

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

More information

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

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level CSE1720 Click to edit Master Week text 08, styles Lecture 13 Second level Third level Fourth level Fifth level Winter 2014! Thursday, Feb 27, 2014 1 General Info Continuation of Chapter 9 Read Chapter

More information

Object Oriented Programming. Java-Lecture 11 Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism Object Oriented Programming Java-Lecture 11 Polymorphism Abstract Classes and Methods There will be a situation where you want to develop a design of a class which is common to many classes. Abstract class

More information

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

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Object-Oriented Programming Review 2: Object-Oriented Programming Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Review 2: Object-Oriented Programming 1 / 14 Topics

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x

More information

Inheritance & Polymorphism

Inheritance & Polymorphism Inheritance & Polymorphism Procedural vs. object oriented Designing for Inheritance Test your Design Inheritance syntax **Practical ** Polymorphism Overloading methods Our First Example There will be shapes

More information

Making New instances of Classes

Making New instances of Classes Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using

More information

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary Programming in Java, 2e Sachin Malhotra Saurabh Choudhary Chapter 5 Inheritance Objectives Know the difference between Inheritance and aggregation Understand how inheritance is done in Java Learn polymorphism

More information

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: has a CSC Employee. Supervisor CSC 143 Object & Class Relationships Inheritance Reading: Ch. 10, 11 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 22 Polymorphism using Interfaces Overview Problem: Can we delay decisions regarding which method to use until run time? Polymorphism Different methods

More information

More On inheritance. What you can do in subclass regarding methods:

More On inheritance. What you can do in subclass regarding methods: More On inheritance What you can do in subclass regarding methods: The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

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

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods. Final Exam Polymorphism Time: Thursday Dec 13 @ 4:30-6:30 p.m. November 26, 2007 Location: Curtiss Hall, room 127 (classroom) ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor CSE 143 Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches dog Dog

More information

Inheritance, polymorphism, interfaces

Inheritance, polymorphism, interfaces Inheritance, polymorphism, interfaces "is-a" relationship Similar things (sharing same set of attributes / operations): a group / concept Similar groups (sharing a subset of attributes / operations): a

More information

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: has a CSE143 Sp Student. CSE 143 Java Object & Class Relationships Inheritance Reading: Ch. 9, 14 Relationships Between Real Things Man walks dog Dog strains at leash Dog wears collar Man wears hat Girl feeds dog Girl watches

More information

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?

QUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? QUIZ Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? Or Foo(x), depending on how we want the initialization

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics Inf1-OP Inheritance Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein School of Informatics March 12, 2018 UML Class Diagrams UML: language for specifying and visualizing OOP software

More information

CS Programming I: Inheritance

CS Programming I: Inheritance CS 200 - Programming I: Inheritance Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624 Inheritance

More information

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

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Java Inheritance Written by John Bell for CS 342, Spring 2018 Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources. Review Which of the following is true? A. Java classes may either

More information

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

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?

More information

Instance Members and Static Members

Instance Members and Static Members Instance Members and Static Members You may notice that all the members are declared w/o static. These members belong to some specific object. They are called instance members. This implies that these

More information

[ L5P1] Object-Oriented Programming: Advanced Concepts

[ L5P1] Object-Oriented Programming: Advanced Concepts [ L5P1] Object-Oriented Programming: Advanced Concepts Polymorphism Polymorphism is an important and useful concept in the object-oriented paradigm. Take the example of writing a payroll application for

More information

Inheritance Motivation

Inheritance Motivation Inheritance Inheritance Motivation Inheritance in Java is achieved through extending classes Inheritance enables: Code re-use Grouping similar code Flexibility to customize Inheritance Concepts Many real-life

More information

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding Java Class Design Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding eugeny.berkunsky@gmail.com http://www.berkut.mk.ua Objectives Implement encapsulation Implement inheritance

More information

type conversion polymorphism (intro only) Class class

type conversion polymorphism (intro only) Class class COMP 250 Lecture 33 type conversion polymorphism (intro only) Class class Nov. 24, 2017 1 Primitive Type Conversion double float long int short char byte boolean non-integers integers In COMP 273, you

More information

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School Class Hierarchy and Interfaces David Greenstein Monta Vista High School Inheritance Inheritance represents the IS-A relationship between objects. an object of a subclass IS-A(n) object of the superclass

More information

Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1

Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1 Inheritance Reuse of code Extension and intension Class specialization and class extension Inheritance The protected keyword revisited Inheritance and methods Method redefinition The composite design pattern

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

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

CSEN401 Computer Programming Lab. Topics: Object Oriented Features: Abstraction and Polymorphism 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

More information

Programming in C# Inheritance and Polymorphism

Programming in C# Inheritance and Polymorphism Programming in C# Inheritance and Polymorphism C# Classes Classes are used to accomplish: Modularity: Scope for global (static) methods Blueprints for generating objects or instances: Per instance data

More information

Classes and Inheritance Extending Classes, Chapter 5.2

Classes and Inheritance Extending Classes, Chapter 5.2 Classes and Inheritance Extending Classes, Chapter 5.2 Dr. Yvon Feaster Inheritance Inheritance defines a relationship among classes. Key words often associated with inheritance are extend and implements.

More information

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

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University OOP Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation Inheritance

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

Inheritance and object compatibility

Inheritance and object compatibility Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not the other way around Examples: reference/pointer can

More information

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics

Inf1-OOP. Inheritance and Interfaces. Ewan Klein, Perdita Stevens. January 12, School of Informatics Inf1-OOP Inheritance and Interfaces Ewan Klein, Perdita Stevens School of Informatics January 12, 2013 Encapsulation Again Inheritance Encapsulation and Inheritance The Object Superclass Flat vs. Nested

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 8(b): Abstract classes & Polymorphism Lecture Contents 2 Abstract base classes Concrete classes Polymorphic processing Dr. Amal Khalifa,

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

Practice for Chapter 11

Practice for Chapter 11 Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing

More information

Upcasting. Taking an object reference and treating it as a reference to its base type is called upcasting.

Upcasting. Taking an object reference and treating it as a reference to its base type is called upcasting. 7. Polymorphism 1 Upcasting Taking an object reference and treating it as a reference to its base type is called upcasting. class Instrument { public void play () { public class Wind extends Instrument

More information