Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Size: px
Start display at page:

Download "Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal"

Transcription

1 Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

2 Lesson Goals Define and discuss abstract classes Define and discuss abstract methods Introduce polymorphism Much of the information in this section is adapted from: Java Illuminated 5 TH Edition, Anderson, Julie and Franceschi Herve, Jones and Bartlett, 2019 Starting Out With Objects From Control Structures Through Objects, Gaddis, Tony, Pearson Publishing,

3 What Is An Abstract Class In the last section we learned that classes in a hierarchy are related by the is-a relationship. For example, a Nissan is-a Automobile, and a Sentra is-a Nissan. Java has features that allow programs to establish and work with hierarchies. Much of the power of object oriented programming comes from this. An abstract class is a class that cannot be instantiated but that can be the parent of other classes. This is useful when you have a broad concept (like Automobile) but actual objects must be specific types (like Sentra). In this lesson we will look at a hierarchy of cards 3

4 A Sample Card Hierarchy 4

5 Abstract Classes An abstract class in Java is a class that is never instantiated. Its purpose is to be a parent to several related classes. The children classes inherit from the abstract parent class. It is defined like this: abstract class ClassName {..... // definitions of methods and variables } Access modifiers such as public can be placed before abstract. Even though it can not be instantiated, an abstract class defines methods and variables that children classes inherit, as we will shortly describe 5

6 Abstract Methods An abstract method has no body. It declares an access modifier, return type, and method signature followed by a semicolon. It has no statements. A non-abstract child class inherits the abstract method and must define a non-abstract method that matches the abstract method. Abstract classes can (but don't have to) contain abstract methods. Also, an abstract class can contain non-abstract methods, which will be inherited by the children. An abstract child of an abstract parent does not have to define non-abstract methods for the abstract signatures it inherits. This means that there may be several steps between an abstract base class to a child class that is completely non-abstract. (You don t need to define each method the first step down. 6

7 Defining An Abstract Method To declare a method as abstract, include the abstract keyword in the method header, and end the header with a semicolon: accessmodifier abstract returntype methodname( argument list ); Note: The semicolon at the end of the header indicates that the method has no code. We do not use opening and closing curly braces.{ 7

8 Method Signature Quick Reminder: A signature looks like this: somemethod( int, double, String ) The return type is not part of the signature. The names of the parameters do not matter, just their types. The name of a method is not enough to uniquely identify it. There may be several versions of a method, each with different parameters. The types in the parameter are needed to specify which method you want. 8

9 The Structure Of An Abstract Class A simple framework for abstraction. Note that the method has no body abstract class Card { protected String recipient; // name of who gets the card public abstract void greeting(); // abstract greeting() method - There is no body } Since no constructor is defined in Card the default noargument constructor is automatically supplied by the compiler. However, this constructor cannot be used directly because no Card object can be constructed. Why? Because abstract classes can t be used to create objects. 9

10 Extending An Abstract Class (1) Below is an example that extends Card class Holiday extends Card { public Holiday( String r ) { recipient = r; // recipient in Card is protected, so this works } public void greeting() { System.out.printf("Dear %s\n", recipient); System.out.printf("Season's Greetings!\n"); } } 10

11 Extending An Abstract Class (2) The class Holiday is not an abstract class. Objects can be instantiated from it. Its constructor implicitly calls the no-argument constructor in its parent, Card, which calls the constructor in Object. So even though it has an abstract parent, a Holiday object is just as much an object as any other. Notes: Holiday inherits the abstract method greeting() from its parent. Holiday must define a greeting() method that includes a method body (statements between braces). The definition of greeting() must match the signature given in the parent. If Holiday did not define greeting(), then Holiday must be declared to be an abstract class. This would make it an abstract child of an abstract parent. 11

12 Abstract Classes Can Have Non-Abstract Methods Not everything defined in an abstract classes must be abstract. The variable recipient is defined in Card and inherited in the usual way. However, if a class contains even one abstract method, then the class itself has to be declared to be abstract. See Card.java, Holiday.java and CardTester.java for a very simple example 12

13 Why Use Abstract Classes Abstract classes are used to organize programs. Of course the same program can be organized in many ways. Our example program could be written without an abstract class. But a real-world application might have hundreds of classes. Grouping classes together is important in keeping a program organized and understandable. The advantage of using an abstract class is that you can group several related classes together as siblings. The picture shows this program after its object has been constructed. Look at CardTesterV2.java to see how we can instantiate a Holiday Card with different greetings 13

14 Multiple Classes From A Single Abstraction We can create multiple classes from a single abstraction, and then create objects from any of those classes See Holiday.java, Valentine.java, Birthday.java and CardTesterV3.java Remember You can t instantiate an object from an abstract class 14

15 Summary Of Abstract Classes An abstract class is intended to be extended but not instantiated. Usually (but not required), the abstract class contains one or more abstract methods. An abstract method specifies an API but does not provide an implementation. The abstract method is used as a pattern for a method the subclasses should implement. An abstract class cannot be used to instantiate objects. However, an object reference to an abstract class can be declared. We use this capability in polymorphism, discussed later. An abstract class can be extended. Subclasses can complete the implementation. Objects of those subclasses can be instantiated. 15

16 Restriction When Defining Abstract Methods An abstract method definition consists of: optional access modifier (public, private, and others), the reserved word abstract, the type of the return value, a method signature, a semi-colon. no braces for a body abstract methods can be declared only within an abstract class. An abstract method must consist of a method header followed by a semicolon. abstract methods cannot be called. abstract methods cannot be declared as private or static. A constructor cannot be declared abstract. 16

17 17

18 What Is Polymorphism? An important concept in inheritance is that an object of a subclass is also an object of any of its superclasses. That concept is the basis for an important OOP feature called polymorphism. Polymorphism means "having many forms." In Java, it means that one variable might be used with several objects of related classes at different times in a program. Polymorphism simplifies the processing of various objects in the same class hierarchy because we can use the same method call for any object in the hierarchy using a superclass object reference. 18

19 Using Polymorphism To use polymorphism, these conditions must be true: The classes are in the same hierarchy. All subclasses override the same method(s). A subclass object reference is assigned to a superclass object reference. The superclass object reference is used to call the overridden method. 19

20 What Are Descendants? What types of objects can a reference variable refer to? A variable can hold a reference to an object whose class is a descendant of the class of the variable. A descendant of a class is a child of that class, or a child of a child of that class, and so on. Siblings are not descendants of each other You don t inherit anything from your brother or sister! 20

21 An Example Of Polymorphism In the example below we create a variable card of type Card We can now use this variable for any subclass of that superclass public class CardTesterV4 { public static void main ( String[] args ) { Card card = new Holiday( "Amy" ); card.greeting(); //Invoke a Holiday greeting() card = new Valentine( "Bob", 3 ); card.greeting(); //Invoke a Valentine greeting() card = new Birthday( "Cindy", 17 ); card.greeting(); //Invoke a Birthday greeting() } } 21

22 Snap Check 1 Here are some variable declarations: Card c; Birthday b; Valentine v; Holiday h; Which of the following are correct given our prior class definitions? c = new Valentine("Debby", 8); b = new Valentine("Elroy", 3); v = new Valentine("Fiona", 3); h = new Birthday ("Greg", 35); 22

23 Snap Check 1 Answers Card c; Birthday b; Valentine v; Holiday h; c = new Valentine("Debby", 8); //OK b = new Valentine("Elroy", 3); //WRONG v = new Valentine("Fiona", 3); //OK h = new Birthday ("Greg", 35); //WRONG 23

24 Snap Check 2 Given the definitions below and the Hierarchy to the left: Rodent rod; Rat rat; Mouse mou; Fill in the chart code section OK or Not? code section OK or Not? rod = new Rat(); mou = new Rat(); rat = new Rodent(); rat = new FieldMouse(); rod = new FieldMouse(); mou = new Rodent(); rat = new LabRat(); rat = new Mouse(); 24

25 Snap Check 2 Answers Giventhe definitions below and the Hierarchy to the left: Rodent rod; Rat rat; Mouse mou; Fill in the chart code section OK or Not? code section OK or Not? rod = new Rat(); mou = new Rat(); rat = new Rodent(); rat = new FieldMouse(); OK Wrong Wrong Wrong rod = new FieldMouse(); mou = new Rodent(); rat = new LabRat(); OK Wrong OK rat = new Mouse(); Wrong 25

26 Extending Classes and Polymorphism class YouthBirthday extends Birthday { public YouthBirthday ( String r, int years ) { super ( r, years ) } // additional method---does not override parent's method Different Signature public void greeting( String sender ) { super.greeting(); System.out.printf("How you have grown!!\n\n"); System.out.printf("Love, %s\n, sender); } } See CardTestV5.java, YouthBirthday.java, AdultBirthday.java 26

27 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (1) There are two approaches to refer a subclass object. Both have some advantages/disadvantages over the other. The declaration affect is seen on methods that are visible at compile-time. First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to a refer any subclass object derived from that superclass. If the methods are present in SuperClass, but overridden by SubClass, it will be the overridden method that will be executed. Second approach (Referencing using subclass reference) : A subclass reference can be used to refer its object. See Programs Bicycle.java, MountainBike.java, TestBikes.java 27

28 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (2) The object of MountainBike class is created which is referred by using subclass reference mb1. MountainBike mb1 = new MountainBike(3, 100, 25); Using this reference we will have access both parts(methods and variables) of the object defined by the superclass or subclass. See below image for clear understanding. 28

29 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (3) Now we again create object of MountainBike class but this time it is referred by using superclass Bicycle reference mb2. Using this reference we will have access only to those parts(methods and variables) of the object defined by the superclass. Bicycle mb2 = new MountainBike(4, 200, 20); 29

30 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (4) If there are methods present in super class, but overridden by subclass, and if object of subclass is created, then whatever reference we use(either subclass or superclass), it will always be the overridden method in subclass that will be executed. In our example, we have seen that by using reference mb2 of type Bicycle, we are unable to call subclass specific methods or access subclass fields. In general, a superclass reference cannot reference subclass specific methods This problem can be solved using type casting in java. For example, we can declare another reference say mb3 of type MountainBike and assign it to mb2 using typecasting. // declaring MountainBike reference MountainBike mb3; // assigning mb3 to mb2 using typecasting. mb3 = (MountainBike)mb2; 30

31 Referencing Subclass Objects with Subclass vs Superclass Reference A Deeper Explanation (5) Summary Of Polymorphic Reference Usage subclass v. superclass Advantage We can use superclass reference to hold any subclass object derived from it. Disadvantage By using superclass reference, we will have access only to those parts(methods and variables) of the object defined by the superclass. For example, we can not access seatheight variable or call setheight(int newvalue) method using Bicycle reference in above first example. This is because they are defined in subclass not in the superclass. 31

32 The instanceof Operator (1) We ve already been using this operator in our equals() methods. Look at the example below: Object obj; YouthBirthday ybd = new YouthBirthday( "Ian", 4 ); String str = "Yertle"; obj = ybd; if ( obj instanceof YouthBirthday ) ((YouthBirthday)obj).greeting(); else if ( obj instanceof String ) System.out.printf( %s\n, (String)obj ); 32

33 The instanceof Operator (2) The format of instance of is: variable instanceof Class A typecast is used to tell the compiler what is really in a variable that itself is not specific enough. You have to tell the truth. In a complicated program, a reference variable might end up with any of several different objects, depending on the input data or other unpredictable conditions. The instanceof operator evaluates to true or false depending on whether the variable refers to an object of its operand. Also, instanceof will return true if variable is a descendant of Class. It can be a child, a grandchild, a greatgrandchild, or... of the class. 33

34 Programming Exercise 1 An abstract class Extending the abstract class Shape Create an abstract superclass Shape. Shape has two abstract methods, perimeter and area, and a final constant field named PI. Create two non-abstract subclasses, one encapsulating a Circle, the other a Rectangle. Rectangle has two additional attributes, length and width of type double. Circle has one additional attribute, its radius of type double. Write a TestShape class with a main method that tests out the above. Read in the length and width of a rectangle and print out the perimeter and area. Read in the radius of a rectangle and print out the perimeter (circumference) and area. 34

Reviewing Java Implementation Of OO Principles CSC Spring 2019 Howard Rosenthal

Reviewing Java Implementation Of OO Principles CSC Spring 2019 Howard Rosenthal Reviewing Java Implementation Of OO Principles CSC 295-01 Spring 2019 Howard Rosenthal Course References Materials for this course have utilized materials in the following documents. Additional materials

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

Interfaces CSC 123 Fall 2018 Howard Rosenthal

Interfaces CSC 123 Fall 2018 Howard Rosenthal Interfaces CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Defining an Interface How a class implements an interface Using an interface as a data type Default interfaces Implementing multiple interfaces

More information

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

3. Can an abstract class include both abstract methods and non-abstract methods? D Assignment 13 Abstract Classes and Polymorphism CSC 123 Fall 2018 Answer Sheet Short Answers. Multiple Choice 1. What is an abstract class? C A. An abstract class is one without any child classes. B. An

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

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

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

Computer Science 210: Data Structures

Computer Science 210: Data Structures Computer Science 210: Data Structures Summary Today writing a Java program guidelines on clear code object-oriented design inheritance polymorphism this exceptions interfaces READING: GT chapter 2 Object-Oriented

More information

CS Week 14 Page 1

CS Week 14 Page 1 CS 201 -- Week 14 Accelerated Intro to Computer Science (Java) Reading: 1. Deitel & Deitel, Chapters 10, 14 Objectives: 1. Continue discussing Object Oriented Programming 2. Learn more about Files and

More information

A Formal Presentation On Writing Classes With Rules and Examples CSC 123 Fall 2018 Howard Rosenthal

A Formal Presentation On Writing Classes With Rules and Examples CSC 123 Fall 2018 Howard Rosenthal A Formal Presentation On Writing Classes With Rules and Examples CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Defining a Class Defining Instance Variables Writing Methods The Object Reference this 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

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

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

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

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

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

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

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 & 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

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Understand Object Oriented Programming The Syntax of Class Definitions Constructors this Object Oriented "Hello

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

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

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

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

Inheritance, part 2: Subclassing. COMP 401, Spring 2015 Lecture 8 2/3/2015

Inheritance, part 2: Subclassing. COMP 401, Spring 2015 Lecture 8 2/3/2015 Inheritance, part 2: Subclassing COMP 401, Spring 2015 Lecture 8 2/3/2015 Motivating Example lec8.ex1.v1 Suppose we re writing a university management system. Interfaces: Person get first and last name

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

Inheritance. The Java Platform Class Hierarchy

Inheritance. The Java Platform Class Hierarchy Inheritance In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those

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

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

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

Lecture 2: Java & Javadoc

Lecture 2: Java & Javadoc Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

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

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

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

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

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

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

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

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

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

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

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

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

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

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass? COMP9024: Data Structures and Algorithms Week One: Java Programming Language (II) Hui Wu Session 1, 2014 http://www.cse.unsw.edu.au/~cs9024 Outline Inheritance and Polymorphism Interfaces and Abstract

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

Chapter 11: Inheritance

Chapter 11: Inheritance Chapter 11: Inheritance Starting Out with Java: From Control Structures through Objects Fourth Edition by Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All rights reserved. Reading

More information

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism Ibrahim Albluwi Composition A GuitarString has a RingBuffer. A MarkovModel has a Symbol Table. A Symbol Table has a Binary

More information

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018 Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 4: OO Principles - Polymorphism http://courses.cs.cornell.edu/cs2110/2018su Lecture 3 Recap 2 Good design principles.

More information

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance? CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

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 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

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. 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

Structured Programming

Structured Programming CS 170 Java Programming 1 Objects and Variables A Little More History, Variables and Assignment, Objects, Classes, and Methods Structured Programming Ideas about how programs should be organized Functionally

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

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

Binghamton University. CS-140 Fall Dynamic Types

Binghamton University. CS-140 Fall Dynamic Types Dynamic Types 1 Assignment to a subtype If public Duck extends Bird { Then, you may code:. } Bird bref; Duck quack = new Duck(); bref = quack; A subtype may be assigned where the supertype is expected

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

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8 Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1 Inheritance you know a lot about an object by knowing its class for example what is a Komondor? http://en.wikipedia.org/wiki/file:komondor_delvin.jpg

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 5: Inheritance & Polymorphism Lecture Contents 2 What is Inheritance? Super-class & sub class Protected members Creating subclasses

More information

CST242 Object-Oriented Programming Page 1

CST242 Object-Oriented Programming Page 1 CST4 Object-Oriented Programming Page 4 5 6 67 67 7 8 89 89 9 0 0 0 Objected-Oriented Programming: Objected-Oriented CST4 Programming: CST4 ) Programmers should create systems that ) are easily extensible

More information

Polymorphism and Interfaces. CGS 3416 Spring 2018

Polymorphism and Interfaces. CGS 3416 Spring 2018 Polymorphism and Interfaces CGS 3416 Spring 2018 Polymorphism and Dynamic Binding If a piece of code is designed to work with an object of type X, it will also work with an object of a class type that

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

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

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

Inheritance Abstraction Polymorphism

Inheritance Abstraction Polymorphism CS 117 Fall 2003 Inheritance Abstraction Polymorphism What we'll cover today and Friday Classes and subclasses Abstract classes and abstract methods Polymorphism: what is it and how does it work? Interfaces

More information

Introducing Java. Introducing Java. Abstract Classes, Interfaces and Enhancement of Polymorphism. Abstract Classes

Introducing Java. Introducing Java. Abstract Classes, Interfaces and Enhancement of Polymorphism. Abstract Classes Abstract Classes, and Enhancement of Polymorphism Abstract Classes Designing a hierarchy, it s current (and proper) practice placing in the super-classes all the common methods and data structures required

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

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

Inheritance. A key OOP concept

Inheritance. A key OOP concept Inheritance A key OOP concept Setting the scene Why do we need inheritance? Inheritance enables you to define a new class based upon an existing class. The new class is similar to the existing class, but

More information

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson ) (SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson ) Dongwon Jeong djeong@kunsan.ac.kr; http://ist.kunsan.ac.kr/ Information Sciences and Technology Laboratory, Dept. of

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

More on Inheritance. Interfaces & Abstract Classes

More on Inheritance. Interfaces & Abstract Classes More on Inheritance Interfaces & Abstract Classes Java interfaces A Java interface is used to specify minimal functionality that a client requires of a server. A Java interface contains: method specifications

More information

CLASS DESIGN. Objectives MODULE 4

CLASS DESIGN. Objectives MODULE 4 MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors

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 Inheritance Three main programming mechanisms that constitute object-oriented programming (OOP) Encapsulation

More information

C++ & Object Oriented Programming Concepts The procedural programming is the standard approach used in many traditional computer languages such as BASIC, C, FORTRAN and PASCAL. The procedural programming

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

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at  Interfaces. Today Book-keeping Inheritance Subscribe to sipb-iap-java-students Interfaces Slides and code at http://sipb.mit.edu/iap/java/ The Object class Problem set 1 released 1 2 So far... Inheritance Basic objects,

More information

The Essence of OOP using Java, Nested Top-Level Classes. Preface

The Essence of OOP using Java, Nested Top-Level Classes. Preface The Essence of OOP using Java, Nested Top-Level Classes Baldwin explains nested top-level classes, and illustrates a very useful polymorphic structure where nested classes extend the enclosing class and

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

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

AP CS Unit 6: Inheritance Notes

AP CS Unit 6: Inheritance Notes AP CS Unit 6: Inheritance Notes Inheritance is an important feature of object-oriented languages. It allows the designer to create a new class based on another class. The new class inherits everything

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

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

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

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

Comments are almost like C++

Comments are almost like C++ UMBC CMSC 331 Java Comments are almost like C++ The javadoc program generates HTML API documentation from the javadoc style comments in your code. /* This kind of comment can span multiple lines */ //

More information

Chapter 11 Classes Continued

Chapter 11 Classes Continued Chapter 11 Classes Continued The real power of object-oriented programming comes from its capacity to reduce code and to distribute responsibilities for such things as error handling in a software system.

More information

Inheritance, and Polymorphism.

Inheritance, and Polymorphism. Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to

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

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

Introduction to Java. Handout-1d. cs402 - Spring

Introduction to Java. Handout-1d. cs402 - Spring Introduction to Java Handout-1d cs402 - Spring 2003 1 Methods (i) Method is the OOP name for function Must be declared always within a class optaccessqualifier returntype methodname ( optargumentlist )

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 4(b): Inheritance & Polymorphism Lecture Contents What is Inheritance? Super-class & sub class The object class Using extends keyword

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