html5-img
1 / 43

COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University yingcai@iastate.edu Office: Atanasoff 201 Office Hours: MW 3:00pm-4:00pm. Information Hiding Modularity.

layne
Télécharger la présentation

COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

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

  5. Program File File File Class Variables Statements Constructors Variables File Statements Methods Variables 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

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

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

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

  9. Other Implementations • A same interface can have more than one implementation

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

  11. Implementation of Multiple Interfaces

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

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

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

  15. Static Type vs. Dynamic Type • 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 Dog dog = new Dog(); Bird bird = new Bird(); ISpeaking s = null; s = dog; // OK? s = bird; // OK? d = s; // OK? b = s; // OK?

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

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

  18. Abstract Class and Abstract Method The idea is to eliminate duplicated code 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. Allow different implementation of speak() for different pets

  19. Updated Class Hierarchy

  20. More Example

  21. Implementation through Interface

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

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

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

  25. 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];

  26. // 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);

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

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

  29. 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();

  30. 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; }

  31. 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]; } } }

  32. Static Variables • Also called class variables • Shared by a whole class of objects

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

  34. 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); }

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

More Related