CS-202 Introduction to Object Oriented Programming

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

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

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

CS1150 Principles of Computer Science Objects and Classes

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

Inheritance and Polymorphism

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Java Object Oriented Design. CSC207 Fall 2014

25. Generic Programming

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

Inheritance (continued) Inheritance

Chapter 5 Object-Oriented Programming

What is Inheritance?

Inheritance -- Introduction

INHERITANCE. Spring 2019

Practice for Chapter 11

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

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

COP 3330 Final Exam Review

Inheritance and Polymorphism

CS 251 Intermediate Programming Inheritance

Chapter 11 Inheritance and Polymorphism

CH. 2 OBJECT-ORIENTED PROGRAMMING

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

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

Introduction to Inheritance

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

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

ITI Introduction to Computing II

Polymorphism and Inheritance

Inheritance, Polymorphism, and Interfaces

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

Inheritance (IS A Relationship)

ITI Introduction to Computing II

C++ Important Questions with Answers

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

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

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Programming Exercise 14: Inheritance and Polymorphism

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

Inheritance and object compatibility

Motivations. Chapter 13 Abstract Classes and Interfaces

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

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

Classes and Inheritance Extending Classes, Chapter 5.2

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

CMSC 132: Object-Oriented Programming II

Data Structures (list, dictionary, tuples, sets, strings)

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

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

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Chapter 6 Introduction to Defining Classes

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Programming in C# Inheritance and Polymorphism

Super-Classes and sub-classes

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

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Class, Variable, Constructor, Object, Method Questions

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

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

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

Lecture 18 CSE11 Fall 2013 Inheritance

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

CS Programming I: Inheritance

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

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

Inheritance. The Java Platform Class Hierarchy

Chapter 13 Abstract Classes and Interfaces

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Java: introduction to object-oriented features

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

PROGRAMMING LANGUAGE 2

Chapter 14 Abstract Classes and Interfaces

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

8. Polymorphism and Inheritance

OVERRIDING. 7/11/2015 Budditha Hettige 82

Making New instances of Classes

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

EKT472: Object Oriented Programming. Overloading and Overriding Method

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

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

Programming II (CS300)

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

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

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

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

Exercise: Singleton 1

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

OBJECT ORİENTATİON ENCAPSULATİON

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

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Inheritance CSC 123 Fall 2018 Howard Rosenthal

Java Fundamentals (II)

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Transcription:

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

Introduction to Inheritance

Introduction inheritance: an important and powerful object oriented technique that allows one to define new classes from existing classes. powerful feature for reusing software. defines an is-a relationship between two classes. Example: Suppose you want to define a class to model various shapes (Circles, Rectangles, Triangles, etc.). these classes could have many common features. design the classes to avoid redundancy between them.

Superclasses and Subclasses

Superclasses and Subclasses You can use a class to model objects of the same type. Even if classes are different, they can share common properties and behaviors these can be generalized in a class and then shared by other classes. Assume there are two classes C1 and C2 where C2 "extends" C1. in this case C1 is the superclass, parent class, or base class and C2 is the subclass, child class, extended class, or derived class A subclass inherits all accessible data fields and methods from its superclass, and can even add new data fields and methods.

A First Example Let's design a class to model geometric objects like circles and triangles. Geometric objects have many common properties and behaviors. GeometricObject Class: a general class that can be used to model all geometric objects. has properties color and filled and their getters / setters also has datecreated property and its getter also has a tostring() method to return a string representation of the object.

A First Example The Circle class: a special type of geometric object shares common properties and methods with other geometric objects define Circle to "extend" the GeometricObject class inherits everything from GeometricObject adds some of its own methods. The Rectangle Class: can also be defined as a subclass of GeometricObject inherits everything from GeometricObject adds some of its own methods.

A First Example

A First Example The Circle class uses the following syntax: extends is a keyword which tells the compiler that Circle is a subclass of GeometricObject, thus inheriting from the superclass. the constructor for Circle is implemented by invoking setcolor(), and setfilled() which reside in the parent class inherited by Circle. You may be tempted to do something like this: However, color and filled are private in the GeometricObject class and are only accessible in that class (so not accessible to Circle)

Notes on Inheritance Despite its naming, a subclass is not a subset of its superclass. Usually a subclass contains more information and methods than its superclass. Private data fields in the superclass are never accessible outside of the class. They cannot be used directly in a subclass. They can be accessed / mutated through public getters / setters if these are define in the superclass. Not all is-a relationships should be modeled using inheritance a square is a rectangle, but you should not extend Square from Rectangle width and height properties are not appropriate for a square better option is to define a Square class to extend GeomeotricObject and define a side property.

Notes on Inheritance Inheritance models the is-a relationship don't start extending classes willy-nilly just to reuse methods. it doesn't make sense for a Tree class to extend a Person class even if they share common properties like height and weight. subclasses and superclasses should always have the is-a relationship. Two things to ask for whether or not to use inheritance? do the two classes share common properties (data fields) and behaviors (methods)? does the is-a relationship make sense in the real world?

Notes on Inheritance Example 1: Tree extends Person do the two classes share something in common does the is-a relationship make sense? yes, they both have a height no, because a Tree is not a Person Example 2: Student extends Person do the two classes share something in common yes, they can have common properties does the is-a relationship make sense? yes, because a Student is-a Person

Notes on Inheritance Unlike other languages, Java does not allow you to have multiple inheritance inheriting from more than one class Java classes can only inherit directly from one superclass. (single inheritance) (we will come back to multiple inheritance when we talk about interfaces.)

Using the super Keyword

The super Keyword super is a keyword which refers to the superclass of the class in which super is used super can be used in two ways: call a superclass constructor. call a superclass method.

Calling Superclass Constructors Constructors are not inherited by a subclass and can only be invoked using the super keyword. Examples: super(); //call the no-arg super constructor super(parameters); //call the super constructor with the given parameters NOTE: the use of super to call the superclass constructor MUST be the first statement in the subclass constructor. invoking the superclass constructor with its class name in the subclass is a syntax error

Constructor Chaining A constructor can invoke an overloaded constructor or its superclass constructor. if neither is invoked explicitly, the compiler automatically puts super() as first statement in the constructor. Constructing an instance of a class invokes the constructors of all the superclasses along the inheritance chain. subclass constructors always invoke the superclass constructors before performing their own tasks even if there are multiple levels of inheritance

Constructor Chaining Example See Code: Faculty.java, Employee.java, and Person.java

Constructor Chaining Caution Classes should always define a no-arg constructor to avoid programming errors. Consider: Why does this cause compile errors?

Calling Superclass Methods super can be used to call other methods from the superclass. Syntax: super.method(parameters); printcircle() from the Circle class could be rewritten as follows:

Caution: No super.super.methodname() Assume there are three classes A, B, and C. Assume C inherits from B and B inherits from A A B C Assume A has a method mymethod() which is implemented in B and C Question: if you can use super.mymethod() in B to call A's version of mymethod(), can you also use super.super.mymethod() to call A's version of mymethod() in C? No, this is a syntax error. Only allowed one level of method chaining with super.

Overriding Methods

Overridding Methods override a method: when a subclass modifies the implementation of a method defined in the super class you have already seen this when you "override" the tostring() method. tostring() is defined in the Object class, and can be given a more specific implementation in any class in Java (since all classes are subclasses of Object).

Overridding Methods Rules for Overridding: instance methods can only be overridden if it is accessible (public). if a method defined in the subclass is private in the superclass, the two methods are unrelated. static methods can be inherited, but a static method cannot be overridden if a static method defined in the superclass is redefined in a subclass, the superclass version is "hidden". to access it you need to use SuperClassName.staticMethodName

Overriding Methods vs. Overloading Methods

Overriding vs. Overloading overloading: define multiple methods with the same name, but different method signatures. overloaded methods can be either in the same class or different classes related by inheritance overloaded methods have the same name but different parameter lists overridding: providing a completely new implementation for a method in a subclass. overridden methods are in different classes related by inheritance overridden methods have the exact same signature and return type.

Overriding vs Overloading

Override Annotation To avoid any confusion / mistakes, you can use a special Java syntax called the override annotation to indicate that a method is an override of another method. annotation is @Override and is placed before the method in the subclass. the annotation denotes that the annotated method is required to override a method in the superclass if the method with this annotation does not override it's superclass method, the compiler will report an error. Example: if tostring() is mistyped tostring() a compile error is reported if the annotation is present, no compile error reported if the annotation is omitted.

Override Annotation Example

Polymorphism

Polymorphism According to Liang, the three pillars of object-oriented programming are encapsulation, inheritance, and polymorphism. All classes define a type. lets define two terms: subtype: a type defined by a subclass supertype: a type defined by a superclass Example: We can say that Circle is a subtype of GeometricObject and GeometricObject is a supertype of Circle

Polymorphism Inheritance enables a subclass to inherit features from its superclass with additional new features A subclass is a specialization of its superclass every instance of a subclass is also an instance of its superclass, but the reverse is NOT true. Example: Every Circle is a GeometricObject, but not every GeometricObject is a Circle. Therefore: you can always pass an instance of a subclass, to a parameter of its superclass type polymorphism: a variable of a supertype can refer to a subtype object.

Dynamic Binding

Dynamic Binding dynamic binding: a method can be implemented in several classes along the inheritance chain, and the JVM decides which method to invoke at runtime. As we have already seen, a method can be defined in a superclass and overridden in its subclass. multiple versions of the same method exist along the inheritance chain.

Dynamic Binding Example: tostring() is defined in the Object class, and overridden in GeometricObject Consider: Which version of tostring() gets called here? The Object class's tostring()? The GeometricObject class's tostring()?

Dynamic Binding a variable must declare a type lets introduce two new terms: declared type: the type that declares a variable actual type: the actual class for the object referenced by the variable In the previous example: the declared type of o is Object because o is declared as Object o = the actual type of o is GeometricObject because the variable o references an object created using new GeometricObject()

Dynamic Binding So, to answer the original question, Which version of tostring() is called? Answer: the version invoked is always determined by the actual type of the reference variable Therefore: the GeometricObject version is invoked.

Dynamic Binding When does dynamic binding occur?: at runtime

Casting Objects and the instanceof Operator

Casting Objects and the instanceof Operator Remember casting? char ch = 'k'; int n = (int)ch; Well we can typecast an object reference into another type of object reference

Casting Objects and the instanceof Operator implicit object casting assigning a reference of a subtype, to a reference of the subtype's supertype. this is always allowed because a subtype is always an instance of its supertype...always. Example: GeometricObject go = new Circle();

Casting Objects and the instanceof Operator explicit object casting Example: is the following valid? GeometricObject go = new Circle(); Circle c = go; //no this causes a compile error Why doesn't this work? a Circle is always an instace of GeometricObject, but a GeometricObject is not necessarily an instance of Circle. Can we make this work?.. Yes GeometricObject go = new Circle(); Circle c = (Circle)go;

Casting Objects and the instanceof Operator For the casting to be successful, you MUST always make sure that the object to be cast is an instance of the subclass. If the superclass object is not an instance of the subclass a runtime ClassCastException occurs. Example: If GeometricObject was not an instance of Circle, then it cannot be case into a Circle.

Casting Objects and the instanceof Operator How can you verify that a class is an instance of some other class? the instanceof operator (NOTE: all lowercase) NOTE: all lowercase returns true if Class A is an instanceof Class B Example:

Casting Objects and the instanceof Operator Why is casting objects even necessary? Consider this: Circle is a subclass of GeometricObject Circle defines a getdiameter() method GeometricObject does not define a getdiameter() method. Would the following code be valid?: GeometricObject go = new Circle(); System.out.println(go.getDiameter());

Casting Objects and the instanceof Operator Other things to note:

The Object's equals method

The Object's equals method equals(object) is another method defined in the Object class. public boolean equals(object o) This method tests whether two objects are equal: object1.equals(object2)

The Object's equals method The default implementation: public boolean equals(object obj) { return (this == obj); } doesn't really do much for us only returns whether or not both objects reference the same area in memory Good practice dictates that you should always override this method and implement your own for every class you create which could be compared to other instances of the same class.

The Object's equals method Other Notes:

The protected Data and Methods

The protected Data and Methods Review: private: can be accessed only from inside of the class public: can be accessed from any other class What if you want to allow subclasses to access data fields or methods defined in the superclass directly, but prevent nonsubclasses from accessing these same data fields and methods Use the protected modifier

The protected Data and Methods Rules for Use: private: no modifiers (default): allow members of the class to be accessed directly from any class within the same package but not from other package. protected: hide the members of a class completely so they cannot be accessed directly from outside the class. use private for members which will not be used ANYWHERE outside the class enable the members of the class to be accessed by the subclasses in any package or classes in the same package use protected if they are intended for extenders of the class, but not any other users of the class. public: enable members of the class to be accessed by any class. use public if they are intended for users of the class

The protected Data and Methods Other Notes: private and protected can only be used for members of the class public and default (no modifier) can be used on members of the class as well as the class itself a class with no modifier (a non public class) is not accessible by classes from other packages

The protected Data and Methods

The protected Data and Methods

Preventing Extending and Overriding

Preventing Extending and Overriding A final class cannot be extended A final method cannot be overridden A final data field is a constant If you want to prevent a class from being extended (subclassed) or a method from being overridden by its subclasses you can use the final keyword. Examples: Math, String, StringBuilder, StringBuffer are all final, you cannot make subclasses from them

Preventing Extending and Overriding