CISC370: Inheritance

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

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Sept 26, 2016 Sprenkle - CSCI Documentation is a love letter that you write to your future self. Damian Conway

What is Inheritance?

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

9/19/12. Objectives. Assignment 2 Review. Code Review. Review. Testing. Code Review: Good Use of switch Statement

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

Java Magistère BFA

Rules and syntax for inheritance. The boring stuff

ITI Introduction to Computing II

PIC 20A Number, Autoboxing, and Unboxing

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Why OO programming? want but aren t. Ø What are its components?

ITI Introduction to Computing II

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

1 Shyam sir JAVA Notes

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

Abstract Classes and Interfaces

Inheritance and Polymorphism

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

9/23/15. Objec-ves. Assignment 2 Review. Review STATIC METHODS AND FIELDS. Sta-c Methods/Fields. Sta-c Methods

CMSC 132: Object-Oriented Programming II

Abstract Classes, Exceptions

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

Implements vs. Extends When Defining a Class

Lecture 4: Extending Classes. Concept

Practice for Chapter 11

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

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

Inheritance (continued) Inheritance

Java Object Oriented Design. CSC207 Fall 2014

Programming overview

CS-202 Introduction to Object Oriented Programming

Compaq Interview Questions And Answers

Introduction to Inheritance

Polymorphism. return a.doublevalue() + b.doublevalue();

CS260 Intro to Java & Android 03.Java Language Basics

OBJECT ORİENTATİON ENCAPSULATİON

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java: introduction to object-oriented features

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

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

INHERITANCE. Spring 2019

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Inheritance and Interfaces

Introduction to Object-Oriented Programming

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

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

Objects and Iterators

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

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

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

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Super-Classes and sub-classes

Chapter 9 Inheritance

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

COP 3330 Final Exam Review

Object Oriented Programming. Java-Lecture 11 Polymorphism

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

Class, Variable, Constructor, Object, Method Questions

Objec,ves. Review: Object-Oriented Programming. Object-oriented programming in Java. What is OO programming? Benefits?

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

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Inheritance -- Introduction

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

15CS45 : OBJECT ORIENTED CONCEPTS

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

Lecture 18 CSE11 Fall 2013 Inheritance

CS Programming I: Inheritance

Methods Common to all Classes

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

WA1278 Introduction to Java Using Eclipse

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

[TAP:AXETF] Inheritance

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

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

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Modern Programming Languages. Lecture Java Programming Language. An Introduction

C++ Important Questions with Answers

C08: Inheritance and Polymorphism

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

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Overriding Variables: Shadowing

Subtype Polymorphism

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

Java Fundamentals (II)

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

Chapter 14 Abstract Classes and Interfaces

C10: Garbage Collection and Constructors

Informatik II (D-ITET) Tutorial 6

Java 8 Programming for OO Experienced Developers

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

Chapter 10 Classes Continued. Fundamentals of Java

Core JAVA Training Syllabus FEE: RS. 8000/-

CS 251 Intermediate Programming Inheritance

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

Core Java Contents. Duration: 25 Hours (1 Month)

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Transcription:

CISC370: Inheritance Sara Sprenkle 1 Questions? Review Assignment 0 due Submissions CPM Accounts Sara Sprenkle - CISC370 2 1

Quiz! Sara Sprenkle - CISC370 3 Inheritance Build new classes based on existing classes Allows you to reuse code Start with a Class (superclass) Create another class that extends the class (subclass or derived class) subclass inherits all of superclass s methods and fields (unless they re private) can also override methods use the same name, but the implementation is different Sara Sprenkle - CISC370 4 2

Inheritance Subclass adds methods or fields for additional functionality If the subclass redefines a superclass method, can still call the superclass method on the super object Use extends keyword to make a subclass Sara Sprenkle - CISC370 5 Rooster class Could write class from scratch, but A rooster is a chicken But it adds something to (or specializes) what a chicken is/does The is a relationship Classic mark of inheritance Rooster will be subclass Chicken will be superclass Sara Sprenkle - CISC370 6 3

Rooster class public class Rooster extends Chicken { public Rooster( String name, int height, double weight) { // all instance fields inherited // from super class this.name = name; this.height = height; this.weight = weight; is_female = false; } By default calls super } // new functionality public void crow() { } constructor with no parameters Sara Sprenkle - CISC370 7 Rooster class public class Rooster extends Chicken { public Rooster( String name, int height, double weight) { super(name, height, weight); is_female = false; } Call to super constructor must be first line in constructor // new functionality public void crow() { } } Sara Sprenkle - CISC370 8 4

Constructor Chaining Automatically calls constructor of superclass if not done explicitly super(); What if superclass does not have a constructor with no parameters? Compilation error Forces subclasses to call a constructor with parameters Sara Sprenkle - CISC370 9 Overriding Methods in Superclass public class Rooster extends Chicken { // new functionality public void crow() { } } // overrides superclass; greater gains public void feed() { weight +=.5; height += 2; } Sara Sprenkle - CISC370 10 5

Overriding Methods in Superclass public class Rooster extends Chicken { // new functionality public void crow() { } } // overrides superclass; greater gains public void feed() { // make it relative to Chicken super.feed(); super.feed(); } Sara Sprenkle - CISC370 11 Every object is an instance of Object java.lang lang.object Inherited methods clone Creates and returns a copy of this object. equals Indicates whether some other object is "equal to" this one. finalize Called by the garbage collector on an object when garbage collection determines that there are no more references to the object Sara Sprenkle - CISC370 12 6

Aside on finalize() No deconstructors in Java No explicit freeing of memory Garbage collector calls finalize() Garbage collector is low-priority thread Or runs when available memory gets tight Before can clean up memory, object may have generated temp files or open network connections that should be deleted/closed first Benefits of garbage collection? Sara Sprenkle - CISC370 13 Aside on finalize() Benefits of garbage collection Fewer memory leaks Less buggy code But, memory leaks are still possible Code is easier to write Cost: garbage collection may not be as efficient as explicit freeing of memory Sara Sprenkle - CISC370 14 7

Every object is an instance of Object java.lang lang.object Inherited methods getclass Returns the runtime class of an object. tostring Override to customize printout for use in System.out.println() And others Sara Sprenkle - CISC370 15 Inheritance Tree java.lang lang.object Chicken Rooster Rooster Chicken Object Call constructor of superclass first Know you have the fields of superclass before you implement constructor for your class Sara Sprenkle - CISC370 16 8

Inheritance Tree java.lang lang.object Chicken Rooster Rooster Chicken Object No finalize() chaining Should call super.finalize() inside of finalize method Sara Sprenkle - CISC370 17 Shadowing Superclass Fields Subclass has field with same name as superclass You probably shouldn t t be doing this! But could happen Possibly: more precision for a constant field // this class s s field this.field // this class s s field super.field // super class s field Sara Sprenkle - CISC370 18 9

Access Modifiers (Revisited) public Any class can access private No other class can access (including subclasses) Must use superclass s accessor/mutator methods protected subclasses can access members of package can access other classes cannot access Sara Sprenkle - CISC370 19 Summary of Access Modes Four access modes: Private visible to the class only Public visible to the world Protected visible to the package and all subclasses. Default visible to the package what you get if you don t t provide an access modifier Sara Sprenkle - CISC370 20 10

Member Visibility Accessible to Defining Class Class in same package Subclass in different package Non-subclass different package Public Yes Yes Yes Yes Member Visibility Protected Yes Yes Yes No Package Yes Yes No No Private Yes No No No Sara Sprenkle - CISC370 21 Multiple Inheritance In C++, it is possible for a class to inherit (or extend) more than one superclass. The subclass has the fields from both superclasses This is NOT possible in Java. A class may extend (or inherit from) only one class. There is no multiple inheritance. Sara Sprenkle - CISC370 22 11

Polymorphism You can use a derived class object whenever the program expects an object of the superclass object variables are polymorphic. A Chicken object variable can refer to an object of class Chicken, Hen, Rooster, or any class that inherits from Chicken Chicken[] chickens = new Chicken[3]; chickens[0] = momma; chickens[1] = foghorn; chickens[2] = baby; Sara Sprenkle - CISC370 23 Polymorphism Chicken[] chickens = new Chicken[3]; chickens[0] = momma; chickens[1] = foghorn; chickens[2] = baby; But, chicken[1] is still a Chicken object chicken[1].crow(); will not work Sara Sprenkle - CISC370 24 12

Polymorphism When we refer to a Rooster object through a Rooster object variable, we see it as a Rooster object If we refer to a Rooster object through a Chicken object variable, we see it only as a Chicken object. We cannot assign a superclass object to a derived class object variable A Rooster is a Chicken, but a Chicken is not necessarily a Rooster Sara Sprenkle - CISC370 25 Polymorphism Which method do we call if we call chicken[1].feed() Rooster s s or Chicken s? Sara Sprenkle - CISC370 26 13

Polymorphism Which method do we call if we call chicken[1].feed() Rooster s s or Chicken s? Rooster s! Object is a Rooster The JVM figures out its class at runtime and runs the appropriate method. Dynamic dispatch At runtime, the class of the object is determined. Then, the appropriate method for that class is dispatched. Sara Sprenkle - CISC370 27 Dynamic vs.. Static Dispatch Dynamic dispatch is a property of Java, not object-oriented programming in general. Some OOP languages use static dispatch where the type of the object variable used to call the method determines which version gets run. The primary difference is when the decision on which method to call is made Static dispatch (C#) decides at compile time. Dynamic dispatch (Java) decides at run time. Sara Sprenkle - CISC370 28 14

Feed the Chickens! for( Chicken c: chickens ) { c.feed(); How to read this code? } Dynamic dispatch calls the appropriate method in each case, corresponding to the actual class of each object. This is the power of polymorphism and dynamic dispatch! Sara Sprenkle - CISC370 29 Preventing Inheritance Sometimes, you do not want a class to derive from one of your classes. A class that cannot be extended is known as a final class. To make a class final, simply add the keyword final in front of the class definition: final class Rooster extends Chicken {... } Sara Sprenkle - CISC370 30 15

Final methods It is also possible to make a method inside of a class final. any class derived from this class cannot override the final methods By default, all methods in a final class are final methods. class Chicken {... public final String getname() {... }... } Sara Sprenkle - CISC370 31 Why have final methods and classes? Efficiency the compiler can replace a final method call with an inline method because it does not have to worry about another form of this method that belongs to a derived class. JVM does not need to determine which method to call dynamically Safety no alternate form of the method; straightforward which version of the method you called. Example of final class: System Sara Sprenkle - CISC370 32 16

Explicit Object Casting Just like we can cast variables: double pi = 3.14; int i_pi = (int( int)pi; We can cast objects. Rooster foghorn = (Rooster)chickens[1]; Use casting to use an object in its full capacity after its actual type (the derived class) has been forgotten The Rooster object is referred to only using a Chicken object variable Sara Sprenkle - CISC370 33 Explicit Object Casting chickens[1] refers to an object variable to a Chicken object We cannot access any of the Rooster-specific fields or methods using this object variable. We create a new object variable to a Rooster object Using this variable will allow us to reference the Rooster-specific fields of our object Rooster rooster = (Rooster) chickens[1]; Sara Sprenkle - CISC370 34 17

Object Casting We can do explicit type checking because chickens[1] refers to an object that is actually a Rooster object. For example, cannot do this with chickens[0] because it refers to a Hen (not Rooster) object Rooster rooster = (Rooster) chickens[1]; // OK; chickens[1] refers to a Rooster object Rooster hen = (Rooster) chickens[0]; // ERROR; chickens[1] refers to a Hen object We are promising the compiler that chickens[1] really refers to a Rooster object, although it is an object variable to a Chicken object. If this is not the case, generates an exception. More about exceptions later. Sara Sprenkle - CISC370 35 instanceof Operator Make sure such a cast will succeed before attempting it, using the instanceof operator: if (chickens[1] instanceof Rooster) { rooster = (Rooster)chickens[1]; } operator returns a boolean true if chickens[1] refers to an object of type Rooster false otherwise Sara Sprenkle - CISC370 36 18

Summary of Inheritance Place common operations & fields in the superclass. Remove repetitive code by modeling the is-a hierarchy Move common denominator code up the inheritance chain Protected fields are generally not a good idea. Don t t use inheritance unless all inherited methods make sense Use polymorphism. Sara Sprenkle - CISC370 37 Real-world Example of Inheritance java.net.socket This class implements client sockets. A socket is an endpoint for communication between two machines. java.net.sslsocket This class extends Sockets and provides secure socket using protocols such as the "Secure Sockets Layer" (SSL) or IETF "Transport Layer Security" (TLS) protocols. Such sockets are normal stream sockets, but they add a layer of security protections over the underlying network transport protocol, such as TCP. Sara Sprenkle - CISC370 38 19

Wrapper Classes Wrapper class for each primitive type Sometimes need an instance of an Object To use to store in HashMaps and other collections Include the functionality of parsing their respective data types. int x = 10; Integer y = new Integer(10); Sara Sprenkle - CISC370 39 Wrapper Classes Autoboxing automatically create a wrapper object // implicitly 11 converted to // new Integer(11); Integer y = 11; Autounboxing automatically extract a primitive type Integer x = new Integer(11); int y = x.intvalue intvalue(); int z = x; // implicitly, x is x.intvalue intvalue(); Sara Sprenkle - CISC370 40 20

PACKAGES! Sara Sprenkle - CISC370 41 Abstract Classes Sara Sprenkle - CISC370 42 21

Example of Abstract classes Calendar (abstract) Gregorian Calendar Sara Sprenkle - CISC370 43 ArrayList Dynamically sized array Sara Sprenkle - CISC370 44 22