COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Inheritance Inheritance Reserved word protected Reserved word super
ITEC200 – Week03 Inheritance and Class Hierarchies.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 7 Inheritance, Polymorphism, and Scope.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Writing Classes (Chapter 4)
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
What is inheritance? It is the ability to create a new class from an existing class.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance ITI1121 Nour El Kadri.
Chapter 3: Using Methods, Classes, and Objects
Object Oriented Programming in Java
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Object-Oriented Programming
Object Oriented Programming in java
Presentation transcript:

COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff 201 Office Hours: MW 3:00pm-4:00pm

Information Hiding Modularity The basic idea is to build systems out of components that can be developed independently of each other Reducing coupling between components is the key developing complex systems, not just software

Abstraction View components in terms of their essential features, ignoring details that aren’t relevant to our particular concerns Each component provides a well-defined interface that specifies exactly how we can interact with it

Object-Oriented Programming A system is a collection of interacting objects that communicate through well-defined interfaces An object has three components State: instance variables that hold some values Identity: an object can be referred to and unique identified Operations: public interfaces (application programming interface) A class is a type of an object A class may have many objects

OOP in Java: Class and Object A program consists of one or more classes In java, a class typically takes a single file Point example BankAccount examples Program File Class Variables Constructors Methods Variables Statements

class BankAccount { // account state stored in private variables private float balance; private String name; private String TransactionList; // etc // public interface public void deposit(float amount) { … } public double getCurrentBalance() { … } public double getTransactionList () { … } public Report prepareMonthlyReport() { … } // etc }

Interface An interface in Java defines a set of public methods without bodies For each method, it specifies a method name, parameter types, and return types It is basically a contract between module writers, specifying exactly how they will communicate

Interface Implementation An interface is basically a contract between module writers Bird is called a subtype of ISpeaking and ISpeaking a supertype of Bird

Other Implementations A same interface can have more than one implementation

Some Notes You can declare an object whose type is an interface: ISpeaking b; //OK You cannot instantiate an interface variable ISpeaking b = new Ispeaking(); //illegal An interface variable must refer to an object of a class that implements the interface ISpeaking b = new Bird(); //OK All methods in a java interface are public

Implementation of Multiple Interfaces

Class Extension Share code and reduce redundancy Allow to add new attributes and methods Retriever is a subtype or subclass of Dog; Dog is a supertype or a superclass of Retriever

Class Hierarchy By extension, classes may form a hierarchy Class hierarchy may be described as a class diagram, using Unified Modeling Language (UML) We say Dog “implements” ISpeaking (dot line), Retriever extends Dog (solid line) We also say the subtype relation the “is-a” relation: A Retriever is a type of Dog, and a Dog is a type of ISpeaking.

Polymorphism A variable of a given type T can hold a reference to an object of any of T’s subtypes Ispeaking s = new Dog(“Thunder”, null) The above statement does a few things It invokes a constructor to instantiate an object of type Dog  Some amount of memory is allocated to hold this object The constructor returns a reference to the object (or actually points to the memory address) It declares a variable s of type Ispeaking The value of s is set to be the reference (i.e., memory address) Important Notes A Dog can be referenced by s because every Dog is an ISpeaking object, but not vice verse In general, an object can hold a reference to any of its subtype

Static Type vs. Dynamic Type Dog dog = new Dog(); Bird bird = new Bird(); ISpeaking s = null; s = dog; // OK? s = bird; // OK? d = s; // OK? b = s; // OK? Let p be a reference to an object Static type (compile time type) of P is the type of P when it is declared Dynamic type (runtime type) of P is the type of the object it references

Dynamic binding Let p be a reference to an object When p’s method is invoked, it is the object’s method that gets invoked

Suppose we also want to implement a Cat class now getName() is duplicated

Abstract Class and Abstract Method The idea is to eliminate duplicated code Allow different implementation of speak() for different pets Java Abstract classes are used to declare common characteristics of subclasses. An abstract class cannot be instantiated. It can only be used as a superclass for other classes that extend the abstract class. Abstract classes are declared with the abstract keyword. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.

Updated Class Hierarchy

More Example

Implementation through Interface

Abstract Class and Abstract Method A Java interface is just like an abstract class, except A java class can inherit from only class, but can implement multiple interfaces A Java interface cannot implement any method, it can only contain method prototypes and constants

Access Modifiers private Accessible only within the class, used for implementation details none or “package-private” (almost = protected) Accessible from any class within the package or by a subclass of its class in another package protected Accessible from subclasses, use when you want any subclass to have access to a variable or method that is not public public Accessible from any class

The root of java class hierarchy: java.lang.object toString(): return a string containing the class name and a hex number getClass(): return the object of type Class that represents the runtime class of the object equals(): return if two objects are the same, i.e., in the same memory

Memory Allocation Variable of primitive types Value reference: It references to a memory that store the actual value 8 types (byte, short, int, long, float, double, boolean, char) Allocate at most 8 bytes Variable of non-primitive types (i.e., objects) Object reference: It references to a memory that stores the address of the memory that stores the object Depending on the implementation of JVM, most likely 8 bytes (for 64-bit address space) Array treated as an object int i = 100; Object o = new Object(); int a[] = new int[100]; Object o[] = new Object[100];

// what does this mean? Point r = q ; Point r = new Point(1, 2); Point q = new Point(1, 2); r.equals(q)? String s = “hurry”; String t = “HURRY”.toLowerCase() System.out.println(s == t); System.out.println(s.equals(t);

Copy and Clone() //1. Using constructor pubic Point(Point existing) { this.x = existing.getX(); this.y = existing.getY(); }

Copy and Clone() //2. Ad hoc cloning pubic Point makeClone() { Point copy = new Point(); copy.setX(this.x); copy.setY(this.y); }

Copy and Clone() //2. Ad hoc cloning pubic Point makeClone() { Point copy = new Point(); copy.setX(this.x); copy.setY(this.y); } Uaage: Point p = new Point(2, 4); q = p.makeClone();

Copy and Clone() //3. Overriding Object.clone() pubic Object clone() { Point copy = null; try { // super.clone() creats a copy of // all fileds copy = (Point) super.clone(); } catch (CloneNotSupportedException e) { } return copy; }

Shallow vs Deep Copying public class IntVector { // Dimension (length) of this vector. private int dim; //The coordinates of this vector. private int[] coords; :::: public IntVector(IntVector existing) { dim = existing.dim; coords = new int[dim]; for (int i = 0; i < dim; ++i) { coords[i] = existing.coords[i]; }

Static Variables  Also called class variables  Shared by a whole class of objects

Static Method  Does not implicit pass an object as its parameter Usage: Human.printHumans()

Variable Scope  The scope of a variable is the part of the program in which it is visible  Local variable: defined within a method, ranged from its declaration until the end of the block or for statement in which it is declared public static void main(String[] args) { int sum = 0; for (int i=0; i<=10; i++) { int square = i * i; sum = sum + square; } System.out.println(sum); }

Exception Handling  An exception is any special condition that alters the normal flow of program execution  divided by zero or open a file that does not exist, etc. Exception handler