This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

Similar documents
Bags. Chapter 1. Copyright 2012 by Pearson Education, Inc. All rights reserved

Designing Classes. Appendix D. Slides by Steve Armstrong LeTourneau University Longview, TX 2007, Prentice Hall

First IS-A Relationship: Inheritance

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

Inheritance -- Introduction

More Relationships Between Classes

Practice for Chapter 11

8. Polymorphism and Inheritance

Object Oriented Programming. Java-Lecture 11 Polymorphism

CS-202 Introduction to Object Oriented Programming

What is Inheritance?

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

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

Example: Count of Points

Introduction to Inheritance

Java Fundamentals (II)

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

Inheritance and Polymorphism

CMSC 132: Object-Oriented Programming II

Polymorphism and Inheritance

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

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

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

Inheritance. Chapter 7. Chapter 7 1

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

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

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Inheritance, Polymorphism, and Interfaces

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

Inheritance (Outsource: )

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

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

Inheritance. Transitivity

Java Object Oriented Design. CSC207 Fall 2014

CLASS DESIGN. Objectives MODULE 4

Inheritance (continued) Inheritance

Chapter 6 Reflection

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

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

OBJECT ORİENTATİON ENCAPSULATİON

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

Chapter 5 Object-Oriented Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Class, Variable, Constructor, Object, Method Questions

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

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Example: Count of Points

More on Objects in JAVA TM

Lecture 18 CSE11 Fall 2013 Inheritance

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

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Super-Classes and sub-classes

Declarations and Access Control SCJP tips

JAVA OBJECT-ORIENTED PROGRAMMING

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Chapter 14 Abstract Classes and Interfaces

Programming II (CS300)

CMSC 132: Object-Oriented Programming II

Inheritance - Assignment5

Chapter 11 Classes Continued

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

More about inheritance

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Inheritance and Polymorphism

Chapter 10 Classes Continued. Fundamentals of Java

INHERITANCE. Spring 2019

Inheritance and Interfaces

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Inheritance and Polymorphism

CS260 Intro to Java & Android 03.Java Language Basics

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

Polymorphism and Interfaces. CGS 3416 Spring 2018

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

Java: introduction to object-oriented features

CS313D: ADVANCED PROGRAMMING LANGUAGE

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

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

What are the characteristics of Object Oriented programming language?

Inheritance and Interfaces

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

Check out Polymorphism from SVN. Object & Polymorphism

COP 3330 Final Exam Review

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

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

The class Object. Lecture CS1122 Summer 2008

CSCE3193: Programming Paradigms

ECE 122. Engineering Problem Solving with Java

Computer Science 225 Advanced Programming Siena College Spring Topic Notes: Inheritance

BBM 102 Introduction to Programming II Spring Inheritance

Comp 249 Programming Methodology Chapter 8 - Polymorphism

Programming in C# Inheritance and Polymorphism

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CS Programming I: Inheritance

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CH. 2 OBJECT-ORIENTED PROGRAMMING

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

Transcription:

This week Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces This is a lot of material but we'll be working with these tools the whole semester

Generic Types (One last thing from Appendix B) Slides by Steve Armstrong LeTourneau University Longview, TX 2007, Prentice Hall

Generic Types Consider a class with fields that can be of any class type Use a generic type Follow class name with an identifier enclosed in angle brackets public class MyClass <T> View the OrderedPair class which takes ordered pairs of any type Note sample code using this generic class

More than one generic type In the previous example, the objects in a pair have either the same data type or data types related by inheritance. You can define more than one generic type within a class definition by writing their identifiers, separated by commas, within the angle brackets after the class s name, as in the class Pair shown in Listing B-6. View the Pair class

Question 23 Can you use the class OrderedPair, as defined in Listing B-5, to pair two objects having different and unrelated data types? Why or why not? Question 24 Can you use the class Pair, as defined in the previous segment, to pair two objects having the same data type? Why or why not? Question 25 Using the class Name, as defined previously in this appendix, write statements that pair two students as lab partners. Question 26 Using the class Name, as defined previously in this appendix, write statements that pair your name with the random sequence number given in the int variable number.

23. No. The class defines only one generic type. 24. Yes. You can write the same data type twice to correspond to both S and T. 25. Name kristen = new Name("Kristen", "Doe"); Name luci = new Name("Luci", "Lei"); OrderedPair<Name> labpartners = new OrderedPair<Name>(kristen, luci); 26. Name kristen = new Name("Kristen", "Doe"); Integer seqn = number; Pair<Name, Integer> apair = new Pair<Name, Integer>(kristen, seqn);

Creating Classes from Other Classes Appendix C Slides by Steve Armstrong LeTourneau University Longview, TX 2007, Prentice Hall

Chapter Contents Composition Generic Types Adapters Inheritance Invoking Constructors from Within Constructors Private Fields and Methods of The Base Class Protected Access Overriding, Overloading Methods Multiple Inheritance Type Compatibility and Base Classes The Class Object Abstract Classes and Methods Polymorphism

Composition When a class has a data field that is an instance of another class Example an object of type Student. A "has a" relationship fig 2-1 Click to View Source Code Fig. 2-1 A Student object composed of other objects

Question 1 What data fields would you use in the definition of a class Address to represent a student s address? Question 2 Add a data field to the class Student to represent a student s address. What new methods should you define? Question 3 What existing methods need to be changed in the class Student as a result of the added field that Question 2 described? Question 4 What is another implementation for the default constructor that uses this, as described in Segment B.25 of Appendix B?

1. Some possibilities are roomnumber and dorm, or street, city, state, zip. 2. private Address residence; Add the methods setaddress and getaddress. 3. The constructors, setstudent, and tostring. 4. public Student() { this(new Name(), ""); } // end default constructor

Adapters Use composition to write a new class Has an instance of an existing class as a data field Defines new methods needed for the new class Example a NickName class adapted from class Name View source code of class NickName

Question 5 Write statements that define bob as an instance of NickName to represent the nickname Bob. Then, using bob, write a statement that displays Bob.

5. NickName bob = new NickName(); bob.setnickname("bob"); System.out.println(bob.getNickName());

Inheritance A general or base class is first defined Then a more specialized class is defined by Adding to details of the base class Revising details of the more general class Advantages Saves work Common properties and behaviors are define only once for all classes involved

Inheritance An "is a" relationship Fig. 2-2 A hierarchy of classes.

Question 6 Some vehicles have wheels and some do not. Revise Figure C-2 to organize vehicles according to whether they have wheels.

6. The Vehicle class has two subclasses, WheeledVehicleand WheellessVehicle. The subclasses of WheeledVehicle are Automobile and Wagon. Boat is a subclass of WheellessVehicle. The remaining subclasses are the same as given in the figure.

Inheritance Fig. 2-3 A hierarchy of student classes. View source code of class CollegeStudent

Invoking Constructors from Within Constructors Constructors usually initialize data fields In a derived class The constructor must call the base class constructor Note use of reserved word super as a name for the constructor of the base class When super is used, it must be the first action in the derived constructor definition Must not use the name of the constructor

Private Fields, Methods of Base Class Accessing inherited data fields Not accessible by name within definition of a method from another class including a derived class Still they are inherited by the derived class Derived classes must use public methods of the base class Note that private methods in a base class are also unavailable to derived classes But usually not a problem private methods are used only for utility duties within their class

Protected Access A method or data field modified by protected can be accessed by name only within Its own class definition Any class derived from that base class Any class within the same package A Java package is a collection of classes related to a certain activity, such as graphics: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/package-summary.html

Protected Access Note accessibility of elements of a class C determined by the access modifiers Fig. 2-4

Overriding Methods When a derived class defines a method with the same signature as in base class Same name Same return type Same number, types of parameters Objects of the derived class that invoke the method will use the definition from the derived class It is possible to use super in the derived class to call an overridden method of the base class

Overriding Methods Fig. 2-5 The method tostring in CollegeStudent overrides the method tostring in Student

Overloading a Method When the derived class method has The same name The same return type but Different number or type of parameters Then the derived class has available The derived class method and The base class method with the same name Java distinguishes between the two methods due to the different parameters

Multiple use of super Consider a class derived from a base that itself is derived from a base class All three classes have a method with the same signature The overriding method in the lowest derived class cannot invoke the method in the base class's base class The construct super.super is illegal

Overloading a Method A programmer may wish to specify that a method definition cannot be overridden So that the behavior of the constructor will not be changed This is accomplished by use of the modifier final

Question 7 Question 5 asked you to create an instance of NickName to represent the nickname Bob. If that object is named bob, do the following statements produce the same output? Explain. System.out.println(bob.getNickName()); System.out.println(bob);

7. No. Since getnickname returns a string, the first statement implicitly calls the method tostring defined in the class String. Thus, Bob is displayed. Since the class NickName does not define its own version of tostring, the second statement invokes Object s tostring. The output involves the memory address of the object referenced by bob.

Question 8 Are the two definitions of the constructors for the class Student (Segment C.2) an example of overloading or overriding? Why? Question 9 If you add the method public void setstudent(name studentname, String studentid) to the class CollegeStudent and let it give some default values to the fields year and degree, are you overloading or overriding setstudent? Why?

8. Overloading.The constructors have the same name but different signatures. 9. Overriding. The revised version of setstudent in CollegeStudent has the same signature and return type as the version in the superclass Student.

Multiple Inheritance Some languages allow programmer to derive class C from classes A and B Java does not allow this A derived class can have only one base class Multiple inheritance can be approximated A derived class can have multiple interfaces Described in Chapter 3

Object Types of a Derived Class Given : Class CollegeStudent, Derived from class Student Then a CollegeStudent object is also a Student object In general An object of a derived class is also an object of the base class

Question 10 If HighSchoolStudent is a subclass of Student, can you assign an object of HighSchoolStudent to a variable of type Student? Why or why not? Question 11 Can you assign an object of Student to a variable of type HighSchoolStudent? Why or why not?

10. Yes. You can assign an object of a class to a variable of any ancestor type. An object of type HighSchoolStudent can do anything that an object of type Student can do. 11. No. The Student object does not have all the behaviors expected of a HighSchoolStudent object.

The Class Object Every class is a descendant of the class Object Object is the class that is the beginning of every chain of derived classes It is the ancestor of every other class Even those defined by the programmer http://docs.oracle.com/javase/1.4.2/docs/a pi/java/lang/object.html

Speaking of class Object... Ancestor of all classes defines methods clone(), equals(), tostring(), among others all classes automatically derive these methods from Object to be useful, we have to override them so they work with the details of the class in which they are defined

Overriding the equals method the parameter is class Object, we use a cast to be able to refer to it as a Name or Student or BankAccount or whater class we are defining it for. we can refer to the private data members of that since it is an object of the same class. Here is equals for Name: public boolean equals (Object other){ } if (other instanceof Name){ Name that = (Name) other; return this.first.equals(that.first) && this.last.equals(that.last) } else return false;

Overriding the clone() method Makes an exact duplicate object with same data. joe2 = joe.clone(); We now have two identical objects public Name clone(){ } return new Name(first, last);

Question 12 If sue and susan are two instances of the class Name, what if statement can decide whether they represent the same name?

12. if (sue.equals(susan))

Abstract Classes and Methods Some base classes are not intended to have objects of that type The objects will be of the derived classes Declare that base class to be abstract public abstract class Whatever {... } The designer often specifies methods of the abstract class without a body public abstract void dosomething(); This requires all derived classes to implement this method

Polymorphism When one method name in an instruction can cause different actions Happens according to the kinds of objects that invoke the methods Example The object still remembers it is of type UndergradStudent

Polymorphism Figure 2-6 The method displayat calls the correct version of display.

Polymorphism Which displayat is called Depends on the invoking object's place in the inheritance chain and is not determined by the type of the variable naming the object Fig. 2-7 The variable s is another name for an undergraduate object.

Dynamic Binding The process that enables different objects to Use different method actions For the same method name Objects know how they are supposed to act When an overridden method is used The action is for the method defined in the class whose constructor created the object

Dynamic Binding Fig. 2-8 An object, not its name, determines its behavior.

Question 14 Is a method display with no parameters that is defined explicitly in each of the classes Student, CollegeStudent, and UndergradStudent an example of overloading or overriding? Why? Question 15 Is overloading a method name an example of polymorphism?

14. Overriding. The methods have the same signatures and return types. 15. At one time, overloading was an example of polymorphism. Today, polymorphism describes a situation in which an object determines at execution time which action of a method it will use for a method name that is overridden either directly or indirectly.