Chapter 3: Inheritance and Polymorphism

Size: px
Start display at page:

Download "Chapter 3: Inheritance and Polymorphism"

Transcription

1 Chapter 3: Inheritance and Polymorphism Overview Inheritance is when a child class, or a subclass, inherits, or gets, all the data (properties) and methods from the parent class, or superclass. Just like in human biology, where a child will inherit features and actions (or properties and methods) from the parent, such as eye color and the ability to roll one s tongue in a U-shape, inheritance in Java works the same way. The child class, which is known as a subclass in Java terminology, will get the methods and the properties (instance variables) from its parent class, which is known as the superclass in Java terminology. The purpose of inheritance in Java is to reduce development and maintenance time, as well as conserve resources. It conserves resources by preventing programmers from writing repetitive code. It reduces maintenance time by modularizing the methods. In other words, the programmer would have to change only one program rather than fifty programs if business rules require a coding change. It reduces development and maintenance time by allowing programmers to create a subclass to implement new functionality, rather than change the superclass and possibly cause disruption with other programs that use the superclass. The concept of inheritance in Java is similar to the concept of inheritance in human biology. The child will inherit features and actions from the parent, but the child can also inherit features and actions from the grandparent, the great-grandparent, and so forth. In Java, if the parent (superclass) is a subclass (child) of another class, the subclass (child) of the parent will also inherit from the parent of the parent. For example, if Class C inherits from Class B, and Class B inherits from Class A, Class C will also inherit from Class A. Polymorphism is the ability to have many different forms. Just like in human biology, a child will speak the same language as the parent, but the child may not sound like the parent. The child may have a higher or lower pitched voice, or the child s inflections may be different from the parent. In Java, the subclass (child) may have the same methods has its superclass (parent), but the subclass can rewrite, or override, the functionality of a method or a few methods. The process of rewriting a superclass s method is called method overriding. Polymorphism is flexible if you want to add more functionality to a particular method for a subclass. For example, you may want to perform the same functionality as the superclass, but you want to add more functionality to the method in the subclass. For the C++ Programmers: Single Inheritance versus Multiple Inheritance Unlike C++, Java follows the principle of single inheritance. Single inheritance means that a class can directly inherit from only one class. In other words, a subclass, or child, can only have one superclass, or parent. Multiple inheritance means that a class can directly inherit from many classes. In other words, a subclass, or child, can have many superclasses, or parents. Object: The Ultimate Superclass The Java programming language is class based. Everything written in Java must live within a class. All classes inherit from a class called the Object class. The Object class is the ultimate superclass, or parent. The library is java.lang.object. Even though all classes inherit from the object class, programmers may not explicitly extend the Object class. The relationship is already assumed. The built-in methods of the Object class that can be overwritten are:

2 The built-in methods that are protected are: How to Inherit in Java When creating subclasses in Java, you can inherit from any existing class. You can inherit from a class in Java, or you can inherit from a custom, reusable class. To inherit from a class, you need to add the key phrase extends ClassName, where ClassName is the name of the superclass. For example, when you were creating applets, you were actually creating subclasses of the Applet class. This lesson is going to focus on inheritance from custom, reusable classes. Let s first take a look at a custom class called Circle. import java.awt.*; public class Circle /* the instance variables */ private int x, y, diameter; private boolean filled; private Color c; /* the constructor - the default constructor */ public Circle() x = 10; y = 10; diameter = 50; c = Color.BLACK; filled = false; /* the other constructor */ public Circle(int posx, int posy, int d, Color newcolor, boolean fill) x = posx; y = posy; diameter = d; c = newcolor; filled = fill; /* the methods */

3 public void drawcircle(graphics g) // set the color g.setcolor(c); // draw the circle if (filled == true) g.filloval(x, y, diameter, diameter); else g.drawoval(x, y, diameter, diameter); public void changecolor(color cl) c = cl; public void changeposition(int newx, int newy) x = newx; y = newy; public void fillcircle(boolean fill) filled = fill; public int getdiameter() return diameter; What happens if we want to add more functionality to the Circle class, or we want to change some of the ways the methods work in the Circle class? Well, you could change the Circle class, but the problem is you could adversely affect the way the programs that are using the Circle class works. A solution is to create a child of the Circle class. Let s take a look at the simplest example of inheritance. This program is called CircleEnhanced. The lines are numbered for reference only. 1. public class CircleEnhanced extends Circle public CircleEnhanced() Breaking It Down In line 1, we are performing inheritance by using the keyword extends. Once we say extends Circle, it means that CircleEnhanced inherits the methods, classes and variables from Circle. There is no need to redefine the methods, classes and variables in CircleEnhanced. Even though that we are inheriting from Circle, we are still required to define a constructor. Note that this code is demonstrating the simplest example of inheritance, and it is not a realistic use of inheritance. Let s do a more realistic example of this. What we are going to do is expand the constructor and add two more methods specific to CircleEnhanced. The lines are numbered for reference only. 1. import java.awt.*; 2. public class CircleEnhanced extends Circle

4 3. 4. /** 5. * Predetermines the look of the circle as an open circle in black starting at 10, */ 7. public CircleEnhanced() super(); /** 13. * Draws a face on the graphic area 14. */ 15. public void drawface(graphics g) // this is the face 18. g.drawoval(50, 50, 100, 100); // these are the eyes. Rather than using the drawoval to draw the eyes, 21. // we'll use the fillarc. We are drawing "positive arcs", which means that 22. // you are drawing COUNTERCLOCKWISE g.fillarc(75, 75, 10, 10, 0, 360); 25. g.fillarc(120, 75, 10, 10, 0, 360); // this is the smiley face. We are going to use a drawarc. We are going to draw 28. // a "negative arc", which means that you are drawing CLOCKWISE. 29. g.drawarc(75, 75, 50, 50, 0, -180); /** 33. * Calculate the area of the circle on the screen in pixels and return the area 34. */ 35. public double getarea() // radius is diameter / int radius = super.getdiameter() / 2; // calculate the area and return the area 41. double area = (Math.pow(radius, 2)) * Math.PI; 42. return area; Breaking It Down Notice that in line 1, we are importing the java.awt library. You can import libraries in your reusable classes and subclasses In line 9, we are calling a method called super(). The super() method calls the constructor of the superclass. So, when the user makes an instance of the class CircleEnhanced, the constructor of the CircleEnhanced will make a call to the Circle constructor. In lines 12 through 14 and lines 32 through 34, we are making a Javadoc style comment. This is the comment style that the javadoc utility looks for in the code to write descriptions of the methods. Lines 15 through 30 is a method that is a part of CircleEnhanced. So is lines 35 through 43. In line 38, we are referencing super. The object reference of super means reference the superclass. So, if we want to use a method in the superclass getdiameter, we use the object reference super. NOTE: When you use the super() method or when you call a method in the superclass using the super keyword, that must be the first line in your method. Let s take a look at this in use. The lines are numbered for reference purposes. 1. import java.awt.*;

5 2. import java.applet.*; 3. 4.public class TestCircle extends Applet public void paint(graphics g) // In this example, we are using the Circle class 10. // These are all methods in the Circle Class 11. Circle c = new Circle(); 12. c.fillcircle(true); 13. c.changecolor(color.green); 14. c.drawcircle(g); /* In this example, we are using the CircleEnhanced class 17. * We are going to use methods in the CircleEnhanced class, 18. * and we are going to use methods that actually exist in the 19. * parent class Circle to demonstrate inheritance. 20. */ 21. CircleEnhanced ce = new CircleEnhanced(); 22. ce.fillcircle(true); // in parent - superclass 23. double area = ce.getarea(); // in child - subclass 24. ce.changeposition(50, 50); // in parent - superclass 25. ce.drawcircle(g); // in parent - superclass // now, we are going to write the area of our CircleEnhanced 28. g.drawstring("the area of our custom circle in black is: " + area, 5, 150); Breaking It Down In line 21, we are making an instance of CircleEnhanced. Remember that when we make an instance of the CircleEnhanced class, it is calling the constructor of CircleEnhanced. Remember also that in the CircleEnhanced class, the CircleEnhanced constructor is calling the super() method, which calls the constructor of the parent. In lines 22, 24, and 25, we are calling methods that actually exist in the parent. How Java works is it is going to first look in the class for the methods being called. If the methods do not exist, it will then look in the parent class for the methods. In this case, these methods exist in the parent (super) class of Circle, so it will execute, or run, the code in the methods in the superclass. In line 23, this method exists in the class. Here are the results of this program:

6 Polymorphism in Java Remember that the purpose of making subclasses is to reduce development time. What happens if the functionality in a method of the superclass is not robust enough for the subclass? In other words, what if the subclass is supposed to perform the code in a method of the superclass, but more functionality for that method is needed? Method overriding gives that option. Method overriding is when the programmer rewrites the method in the subclass from the superclass. For example, when you were developing applets, you were performing method overriding when you were writing code for the paint method. Let s take a look at method overriding, or polymorphism in action. In this case, we are going to rewrite the drawcircle() method in CircleEnhanced to perform the same functionality as the parent, but it is also going to write the area of the circle. 1. import java.awt.*; 2. public class CircleEnhanced extends Circle /** 5. * Predetermines the look of the circle as an open circle in black starting at 10, */ 7. public CircleEnhanced() super(); /** 13. * Draws a face on the graphic area 14. */ 15. public void drawface(graphics g) // this is the face 18. g.drawoval(50, 50, 100, 100); // these are the eyes. Rather than using the drawoval to draw the eyes, 21. // we'll use the fillarc. We are drawing "positive arcs", which means that 22. // you are drawing COUNTERCLOCKWISE 23.

7 24. g.fillarc(75, 75, 10, 10, 0, 360); 25. g.fillarc(120, 75, 10, 10, 0, 360); // this is the smiley face. We are going to use a drawarc. We are going to draw 28. // a "negative arc", which means that you are drawing CLOCKWISE. 29. g.drawarc(75, 75, 50, 50, 0, -180); /** 33. * Calculate the area of the circle on the screen in pixels and return the area 34. */ 35. public double getarea() // radius is diameter / int radius = super.getdiameter() / 2; // calculate the area and return the area 41. double area = (Math.pow(radius, 2)) * Math.PI; 42. return area; /* 45. * draw a circle on the graphics area 46. */ 47. public void drawcircle(graphics g) super.drawcircle(g); // run the code in drawcircle in the parent class 50. g.drawstring("the area of this circle is: " + getarea(), 2, 175); Breaking It Down In lines 47 through 51, we are overriding the drawcircle method to not only draw the circle, but also write the area in the graphics area. Again, we are making a reference to the superclass with the keyword super, and we are running the code in the drawcircle method of the superclass. We are going to use the TestCircle program that we used earlier to test our results. Note that we did not have to recompile the TestCircle program. The beauty of Java is the program will know to use the latest compiled versions of the class. There is no need to recompile the program that is making an instance of the class. Also, note that in Java, remember that when we are calling a method of a class, it is going to look in the class first. If it exists in the class, it will perform the method that exists in the class. It will not look further into the relationship. Here are the results of the program:

8 Method, Class and Variable Scope When a variable, method or class is public, it means that all classes can access this. For example, all programs that make an instance of a class can call public methods. Think of public as visible by all. Look at a graphic of class MySample and it s relationship to other sample classes to get a better understanding of public access:

9 When a variable, method or class is protected, it means that the class that has the variable, method or class can access the variable or method. It also means that the class s subclasses (children) can also access the variable, and if the class is part of a package, other classes within the package can access the variable. Look at a graphic of class MySample and it s relationship to other sample classes to get a better understanding of protected access: When a variable, method, or class is private, it means that only the class that has the variable, method and/or class can access the variable. Look at a graphic of class MySample and it s relationship to other sample classes to get a better understanding of private access: When a variable, method, or class has no declaration, it is similar to how the variable is accessed when it s declared as protected, but the class s subclasses (children) cannot access the variable.

10 However, if the children are in the package with the parent, then the children can access the variable directly. Look at a graphic of class MySample and it s relationship to other sample classes to get a better understanding of unspecified access:

ICS 4U. Introduction to Programming in Java. Chapter 10 Notes

ICS 4U. Introduction to Programming in Java. Chapter 10 Notes ICS 4U Introduction to Programming in Java Chapter 10 Notes Classes and Inheritance In Java all programs are classes, but not all classes are programs. A standalone application is a class that contains

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

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

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

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

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

Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden

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

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

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

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using Java Provided Classes In this lesson we'll focus on using the Graphics class and its capabilities. This will serve two purposes: first

More information

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application Last Time v We created our first Java application v What are the components of a basic Java application? v What GUI component did we use in the examples? v How do we write to the standard output? v An

More information

Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction

Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction Class Interaction There are 3 types of class interaction. One

More information

JAVA MOCK TEST JAVA MOCK TEST II

JAVA MOCK TEST JAVA MOCK TEST II http://www.tutorialspoint.com JAVA MOCK TEST Copyright tutorialspoint.com This section presents you various set of Mock Tests related to Java Framework. You can download these sample mock tests at your

More information

Arrays Classes & Methods, Inheritance

Arrays Classes & Methods, Inheritance Course Name: Advanced Java Lecture 4 Topics to be covered Arrays Classes & Methods, Inheritance INTRODUCTION TO ARRAYS The following variable declarations each allocate enough storage to hold one value

More information

INHERITANCE AND EXTENDING CLASSES

INHERITANCE AND EXTENDING CLASSES INHERITANCE AND EXTENDING CLASSES Java programmers often take advantage of a feature of object-oriented programming called inheritance, which allows programmers to make one class an extension of another

More information

Inheritance. Transitivity

Inheritance. Transitivity Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated

More information

8. Polymorphism and Inheritance

8. Polymorphism and Inheritance 8. Polymorphism and Inheritance Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich http://seal.ifi.uzh.ch/info1 Objectives Describe polymorphism and inheritance in general Define interfaces

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

Reusing Classes. Hendrik Speleers

Reusing Classes. Hendrik Speleers Hendrik Speleers Overview Composition Inheritance Polymorphism Method overloading vs. overriding Visibility of variables and methods Specification of a contract Abstract classes, interfaces Software development

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

CIS 110: Introduction to computer programming

CIS 110: Introduction to computer programming CIS 110: Introduction to computer programming Lecture 25 Inheritance and polymorphism ( 9) 12/3/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Inheritance Polymorphism Interfaces 12/3/2011

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

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

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017 Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data

More information

OVERRIDING. 7/11/2015 Budditha Hettige 82

OVERRIDING. 7/11/2015 Budditha Hettige 82 OVERRIDING 7/11/2015 (budditha@yahoo.com) 82 What is Overriding Is a language feature Allows a subclass or child class to provide a specific implementation of a method that is already provided by one of

More information

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

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 (Deitel chapter 9)

Inheritance (Deitel chapter 9) Inheritance (Deitel chapter 9) 1 2 Plan Introduction Superclasses and Subclasses protected Members Constructors and Finalizers in Subclasses Software Engineering with Inheritance 3 Introduction Inheritance

More information

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 1 Problem Ralph owns the Trinidad Fruit Stand that sells its fruit on the street, and he wants to use a computer

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Inheritance (Continued) Polymorphism Polymorphism by inheritance Polymorphism by interfaces Reading for this lecture: L&L 10.1 10.3 1 Interface Hierarchies Inheritance can

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

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

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

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

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 21, 2013 Abstract

More information

Lecture 18 CSE11 Fall 2013 Inheritance

Lecture 18 CSE11 Fall 2013 Inheritance Lecture 18 CSE11 Fall 2013 Inheritance What is Inheritance? Inheritance allows a software developer to derive a new class from an existing one write code once, use many times (code reuse) Specialization

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

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

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Define and discuss abstract classes Define and discuss abstract methods Introduce polymorphism Much of the information

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language Categories of languages that support OOP: 1. OOP support is added to an existing language - C++ (also supports procedural and dataoriented programming) - Ada 95 (also supports procedural and dataoriented

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

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes COMP200 - Object Oriented Programming: Test One Duration - 60 minutes Study the following class and answer the questions that follow: package shapes3d; public class Circular3DShape { private double radius;

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

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

QUESTIONS FOR AVERAGE BLOOMERS

QUESTIONS FOR AVERAGE BLOOMERS MANTHLY TEST JULY 2017 QUESTIONS FOR AVERAGE BLOOMERS 1. How many types of polymorphism? Ans- 1.Static Polymorphism (compile time polymorphism/ Method overloading) 2.Dynamic Polymorphism (run time polymorphism/

More information

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods Lecture 12 Summary Inheritance Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods Multiplicity 1 By the end of this lecture, you will

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

Week 9. Abstract Classes

Week 9. Abstract Classes Week 9 Abstract Classes Interfaces Arrays (Assigning, Passing, Returning) Multi-dimensional Arrays Abstract Classes Suppose we have derived Square and Circle subclasses from the superclass Shape. We may

More information

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

Chapter 10 Classes Continued. Fundamentals of Java

Chapter 10 Classes Continued. Fundamentals of Java Chapter 10 Classes Continued Objectives Know when it is appropriate to include class (static) variables and methods in a class. Understand the role of Java interfaces in a software system and define an

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

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

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

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

CSE115 Introduction to Computer Science for Majors I Spring 2008 Final Exam. First/Given Name (PRINT) May 6, 2008

CSE115 Introduction to Computer Science for Majors I Spring 2008 Final Exam. First/Given Name (PRINT) May 6, 2008 CSE115 Introduction to Computer Science for Majors I Spring 2008 Final Exam First/Given Name (PRINT) May 6, 2008 Last/Family Name (PRINT) Person #: Recitation Section: B1: T 2:00pm B2: W 10:00am (Circle

More information

5.6.1 The Special Variable this

5.6.1 The Special Variable this ALTHOUGH THE BASIC IDEAS of object-oriented programming are reasonably simple and clear, they are subtle, and they take time to get used to And unfortunately, beyond the basic ideas there are a lot of

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

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

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

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008 Overview Lecture 7: Inheritance and GUIs Written by: Daniel Dalevi Inheritance Subclasses and superclasses Java keywords Interfaces and inheritance The JComponent class Casting The cosmic superclass Object

More information

Polymorphism and Inheritance

Polymorphism and Inheritance Walter Savitch Frank M. Carrano Polymorphism and Inheritance Chapter 8 Objectives Describe polymorphism and inheritance in general Define interfaces to specify methods Describe dynamic binding Define and

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

IT101. Inheritance, Encapsulation, Polymorphism and Constructors IT101 Inheritance, Encapsulation, Polymorphism and Constructors OOP Advantages and Concepts What are OOP s claims to fame? Better suited for team development Facilitates utilizing and creating reusable

More information

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1 Inheritance & Polymorphism Recap Inheritance & Polymorphism 1 Introduction! Besides composition, another form of reuse is inheritance.! With inheritance, an object can inherit behavior from another object,

More information

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

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance CS257 Computer Science I Kevin Sahr, PhD Lecture 10: Inheritance 1 Object Oriented Features For a programming language to be called object oriented it should support the following features: 1. objects:

More information

CS 11 java track: lecture 3

CS 11 java track: lecture 3 CS 11 java track: lecture 3 This week: documentation (javadoc) exception handling more on object-oriented programming (OOP) inheritance and polymorphism abstract classes and interfaces graphical user interfaces

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 (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Inheritance 2. Inheritance 2. Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria

Inheritance 2. Inheritance 2. Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria Inheritance 2 Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria Wolfgang.Schreiner@risc.jku.at http://www.risc.jku.at Wolfgang Schreiner RISC

More information

Overriding Variables: Shadowing

Overriding Variables: Shadowing Overriding Variables: Shadowing We can override methods, can we override instance variables too? Answer: Yes, it is possible, but not recommended Overriding an instance variable is called shadowing, because

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

class Shape { // Color of the shape. (Recall that class Color // is defined in package java.awt. Assume // that this class has been imported.

class Shape { // Color of the shape. (Recall that class Color // is defined in package java.awt. Assume // that this class has been imported. As another example, consider a program that deals with shapes drawn on the screen. Let's say that the shapes include rectangles, ovals, and roundrects of various colors. (A "roundrect" is just a rectangle

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 (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes Inheritance Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new class is known as subclass. The subclass inherits all of its instances variables and

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

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

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

Programming Exercise 14: Inheritance and Polymorphism

Programming Exercise 14: Inheritance and Polymorphism Programming Exercise 14: Inheritance and Polymorphism Purpose: Gain experience in extending a base class and overriding some of its methods. Background readings from textbook: Liang, Sections 11.1-11.5.

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

CS 162, Lecture 25: Exam II Review. 30 May 2018

CS 162, Lecture 25: Exam II Review. 30 May 2018 CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you

More information

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018 Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside

More information

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance Structural Programming and Data Structures Winter 2000 CMPUT 102: Dr. Osmar R. Zaïane Course Content Introduction Objects Methods Tracing Programs Object State Sharing resources Selection Repetition Vectors

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

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

Inheritance CSC 123 Fall 2018 Howard Rosenthal

Inheritance CSC 123 Fall 2018 Howard Rosenthal Inheritance CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Defining what inheritance is and how it works Single Inheritance Is-a Relationship Class Hierarchies Syntax of Java Inheritance The super Reference

More information

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4 Structural Programming and Data Structures Winter 2000 CMPUT 102: Inheritance Dr. Osmar R. Zaïane Course Content Introduction Objects Methods Tracing Programs Object State Sharing resources Selection Repetition

More information

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science II (20073) Week 1: Review and Inheritance Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system

More information

Sorting. Sorting. Selection sort

Sorting. Sorting. Selection sort Sorting 1 Sorting Given a linear list of comparable objects of the same class (or values of the same type), we wish to sort (or reärrange) the objects in the increasing order. For simplicity, let s just

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

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

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

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof Abstract Class Lecture 21 Based on Slides of Dr. Norazah Yusof 1 Abstract Class Abstract class is a class with one or more abstract methods. The abstract method Method signature without implementation

More information

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

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

2. The object-oriented paradigm!

2. The object-oriented paradigm! 2. The object-oriented paradigm! Plan for this section:! n Look at things we have to be able to do with a programming language! n Look at Java and how it is done there" Note: I will make a lot of use of

More information

Polymorphism: Inheritance Interfaces

Polymorphism: Inheritance Interfaces Polymorphism: Inheritance Interfaces 256 Recap Finish Deck class methods Questions about assignments? Review Player class for HW9 (starter zip posted) Lessons Learned: Arrays of objects require multiple

More information

index.pdf January 21,

index.pdf January 21, index.pdf January 21, 2013 1 ITI 1121. Introduction to Computing II Circle Let s complete the implementation of the class Circle. Marcel Turcotte School of Electrical Engineering and Computer Science Version

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

Everything is an object. Almost, but all objects are of type Object!

Everything is an object. Almost, but all objects are of type Object! Everything is an object Almost, but all objects are of type Object! In Java, every class is actually a subclass of Object...or has a superclass which has Object as superclass... There is a class called

More information

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5 Objective Questions BCA Part III page 1 of 5 1. Java is purely object oriented and provides - a. Abstraction, inheritance b. Encapsulation, polymorphism c. Abstraction, polymorphism d. All of the above

More information