best of spring 2014 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Best of Spring 2014 PowerPoint Presentation
Download Presentation
Best of Spring 2014

Best of Spring 2014

162 Vues Download Presentation
Télécharger la présentation

Best of Spring 2014

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Best of Spring 2014 Lecture 23 4/22/2014

  2. The Evolution of Programming • As complexity continues to grow… • … developing a program as recipe-like sequence of instructions becomes increasingly difficult. • Need to be able to develop and understand our programming more like the way we understand the world. • As a set of interacting abstractions. • With different parts of the program operating at different levels of abstraction. • This is object-oriented programming.

  3. Object-Oriented Programming • Programs expressed as a set of software “objects”. • Each object is associated with data and a set of functions or procedures that operate with that data. • Objects are defined by their “class”. • Each class represents an abstraction. • Abstractions often layered on top of each other and/or composited into more complex abstractions. • Key challenge is developing the appropriate abstractions. • The operation of the program is the result of creating objects and having them interact with each other.

  4. Major Themes Of This Course • Abstraction • Encapsulation • Inheritance • Polymorphism • Delegation • Design Patterns • Asynchronous Programming

  5. A Word About Types Value Types Reference Types String Array Objects typed by their class Classes themselves • Integers • Real numbers • Booleans • Character • Values types are defined entirely by their value. • Reference types are structures in memory. • Address in memory uniquely identifies them. • The “value” of a variable that holds a reference type is this address.

  6. Value Types • Integers • byte, short, int, long • Difference is in size (1, 2, 4, or 8 bytes) • No “unsigned” version • Decimal (255), hexidecimal (0xff), and binary (0b11111111) literal formats • Real Numbers • float, double • Difference is in precision. • Characters • char • Characters in Java are 16-bit Unicode values • Literals use single-quote: ‘c’ • Non-printable escape sequence: ‘\u####’ where # is hex digit. • Example: ‘\u00F1’ for ñ • Logical • boolean • Literals are true and false

  7. Method Signature • Almost everything you need to know about a method is in its signature. • 5 parts to a method signature • Access modifier • public, private, protected, or default (i.e., not specified) • Method type • static or default (i.e., not specified) • The keyword static indicates that this is a “class method”. • If the keyword static is not present, then this is an “instance method”. • Return type • The type of value returned by the method as a result. • If there is no result, then this is indicated by the keyword void. • Method name • Must start with a letter, $, or _ • Can contain letters, numbers, $, or _ • Parameter list • In parenthesis, comma-separated list of parameter variables. • If the method has no parameters, then just: () • Each parameter variable name is preceded by a type declaration.

  8. Calling Methods • Calling a class method: ClassName.methodName(parameter values); • Calling an instance method: objectReference.methodName(parameter values); • Above parameter values is a comma separated list of values. • A value can be also be an expression that results in a value. • Must match in number and type according to method’s signature. • A method call that returns a value can be part of an expression. • intmax_times_min = max(a, b, c) * min(a, b, c);

  9. Java Execution Model • Your program is always executing within the context of some method. • Starts off in the “main” class method defined in whatever class you told the program to start with. • Execution context includes: • Variable names that are in scope. • Parameter names. • When you call a method: • Current context is saved. • A new context is created. • Method parameter names are mapped to values provided when method was called. • As method executes, declared variables become part of this new context. • When a method returns: • Current context is destroyed. • Context where method call occurred is restored. • This is why recursion works.

  10. Strings • a = “A String ”; • a.length(); • 9 • a.charAt(3); • ‘t’ • a.concat(“am I”); • “A String am I” • a + “am I”; • Same as above • a.equals(“B string”); • false • a.substring(2,5); • “Stri” • a.trim(); • “A String” • String class • Sequence of chars • Some common methods: • length() • charAt(intidx) • concat(StringotherString) • Can also use “+” • equals(Objectobj) • Be careful about using “==” • substring(int start, int end) • trim() • Strings are immutable • Operations that change/alter a string are really giving you a new one.

  11. Arrays • Container for a fixed number of values with the same type. • Zero based indexing. • Variables for arrays declared by using [] after type. • Type of the variable is Array • Type of each entry is specified by type name before [] • Empty arrays can be created with new keyword. • Size must be provided. • What do I mean by “empty”? • Literal array syntax can be used to create array from literal values (or expressions). int[] iarray; Declared, but not created. iarray = new int[10]; Now it’s created, but uninitialized. len = iarray.length; Length available as public field. Note, not a method. iarray[0] = 3; 0th item set iarray[-1]; Illegal index iarray[10]; Index out of bounds int[] iarray = {1,2,(2+1)}; Declared and items initialized all in one.

  12. Classes and Objects • Fundamental units of abstraction • Physical Analogy • Classes are like factories • Contain a blueprint for an object • Defines the inner workings (i.e., fields aka members) • Defines what it can do (i.e., instance methods) • Factory itself may have some capabilities • Class members and class methods • Relate to the abstraction as a whole and not to a specific instance. • Objects are what the factory builds • Each object is an instance of a class • Name of the class is the data type of the object. • Which means it is the data type of any variable that can reference the object.

  13. Objects as state • An object is defined by its state • Collection of named fields that represent information about the object • The current values assigned to those fields reflect the “state” of the object • Object design reflects purpose • What fields to include in an object will depend on how that object is to be used and the kinds of operations that object will be involved in.

  14. Principle of Encapsulation • Do not expose the internal state of an object directly. • Protects object fields from being put into an inconsistent or erroneous state. • Avoids situation in which external code is dependent on this specific implementation. • Or said another way: allows for the implementation of an abstraction to be improved/changed without breaking other code. • Separate “exposed” behavior from “internal” behavior • Exposed behavior • Procedures / functions other objects / code expected to interact with. • Internal behavior • Procedures / functions defined only for use by methods that are part of the class.

  15. Encapsulation In PracticePart 1: Do Not Expose Internal State • Make all fields private • Amend field declaration with “private” access modifier. • Provide public methods that retrieve and/or alter properties • Methods that retrieves a property is called a “getter”. • Methods that set a property is called a “setter” • Benefits • Can support “read-only” fields by NOT providing a setter • Setter can validate new value to prevent misuse or illegal values. • Can define derived or complex properties that are actually related to multiple field values.

  16. JavaBeans Conventions • JavaBeans • Software engineering framework • Associated tools • Relies on code following certain conventions • In particular, getters and setters for object properties. • Given type T and property P: • Signature of a getter: public T getP() • Signature of a setter: public void setP(T value)

  17. Encapsulation In PracticePart 2: Separate Exposed Behavior • Define an “interface” for all exposed behavior • In Java, an interface is like a contract. • Indicates that a certain set of public methods are available. • One or more classes can indicate that they implement the interface. • Name of interface can be used as a type name • Just like class names are used as type names. • Value of an interface type variable can be set to any object that is an instance of a class that implements the interface.

  18. Interfaces in Java • Like classes, should go in their own .java file • Should have same name as file • Body of interface is a just list of method signatures. • Implementing classes MUST declare these methods as public • Form: interface InterfaceName { type method1(parameters); type method2(parameters); // etc… } • Classes specify which interfaces they implement with “implements” modifier as in: class ClassName implements InterfaceA, InferfaceB {

  19. Advantage of Encapsulation • Can provide different implementations of the same behavior • lec5.ex1.v7 • Create a new implementation of Point based on polar coordinates.

  20. Exposed vs Internal Behavior • Exposed behavior should be reflected in the interface(s) that a class implements • Recall that any method declared in an interface must be defined by an implementing class as a public method. • Internal behavior should be hidden • Use private modifier on these methods to ensure that access only occurs within the class

  21. The Value of A Reference Variable • A variable for a reference type holds a reference to an object in memory. • Also known as a pointer • The value of this reference is a location in memory. • If you set a reference variable equal to the value of another reference variable, you now have two variables the point to the same object. • More importantly, if you use one variable to change the underlying object, the other variable “sees” that change. • Really because there is only one object with two variables that point to it. • lec6.ex1

  22. null references • The value null is valid for any reference type variable • Really means no value at all. • Or in other words, this variable doesn’t point to anything. • Any attempt to access instance fields or methods will result in NullPointerException • If a variable could legitimately be null, then your code needs to check for null before trying to dereference it. • lec6.ex2

  23. The Merits of Immutability • An immutable object is one whose fields (i.e., state) are set upon construction and do not change. • Implication: no setters, just getters • Why immutability? • Can be shared as a part of a plurality of other objects without danger. • Automatically “thread-safe”

  24. Polymorphism • Poly = many, morph = forms • General principle of providing access to an abstraction or method in many forms • Idea is that different forms “fit” different contexts • Note: underlying functionality is the same. • In OO programming, principle is evident in a number of different places. • Constructor overloading • Method overloading

  25. Constructors • What happens when you don’t define a constructor. • Default constructor with no arguments. • Creates new object with all fields set to default value • Numeric fields set to 0 • Boolean fields set to false • String, Array, and any other sort of reference value field set to null. • lec6.ex5.v1

  26. Constructor Overloading • Can define multiple versions of the constructor. • Distinguished from each other by type and number of parameters • Must be some difference otherwise the compiler won’t be able to tell them apart. • When you use the constructor, the right one will be chosen based on the parameters provided. • Note that if you still want a default no-argument constructor, you have to provide it explicitly. • lec6.ex5.v2

  27. Constructor Chaining • Common pattern is to “chain” one constructor off of another. • First line of code in the constructor must be the this keyword as a function with parameters • Matching constructor is called first and allowed to execute. • Then remaining code in original constructor called. • Can chain multiple constructors one on to another • lec6.ex5.v3

  28. Method Overloading • Regular methods can also be overloaded • Same method name defined more than once. • Return type may not be the same. • But usually is. • Method type must be the same. • Instance method or static class method • Parameter list must somehow be different • Again, this is how the compiler knows which one is meant. • Either different in number or type (or both) • One version can call another • No restrictions on when • No special syntax • lec5.ex5.v4, lec6.ex5.v5

  29. Why Overload? • Provides access to constructor / method in a more context specific way. • Limitations of overloading • Does not handle the case when you have two different situations that aren’t distinguished by the number or type of parameters being passed.

  30. Arrays as Reference Types • Same reference, same array • Implication for arrays passed to methods • When an array is passed to a method, any changes that the method makes to its elements is permanent. • Potential danger with object state • If holding object state in an array, easy to accidentally break encapsulation and expose object state to alteration. • Array cloning • Easy way to create a “shallow” copy of an array • Just call clone() method • Result will be a new array of same size with same values or references

  31. Multidimensional Arrays • Multidimension array is simply an array of arrays • Fill out dimensions left to right. int[][] marray = new int[5][]; for(inti=0; i<5; i++) { marray[i] = new int[10]; } • Each Sub-dimension can have independent size. • Sometimes known as as a “ragged” or “uneven” array int[][] marray = new int[5][]; for (inti=0; i<5; i++) { marray[i] = new int[i+1]; } • If each sub-dimension is same size, can create with a single new statement • int[][] marray = new int[5][10];

  32. Java Collection Framework • Arrays are not resizeable • Often need a collection of items that acts like an array that can grow or shrink • Java Collection Framework • In package java.util • Defines a set of interfaces for resizeable collections • List • Ordered by integer index • Set • Unordered, no duplicate elements • Map • Indexed by an arbitrary key • Sometimes known as a “dictionary” • Provides a set of classes that implement these interfaces in specific ways • Examples for List: ArrayList, LinkedList,

  33. Iterator Design Pattern • “Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation” • Gang of Four, Design Patterns • Consider: for(inti=0; i<slist.size(); i++) { Song next_song = slist.get(i); // Do something with next_song. }

  34. Components of Iterator Pattern • Collection object is “iterable” • Provides a method that returns an object that acts as an iterator. • Iterator object provides access to the elements in turn. • At the very least: • A method to test whether more items exist. • A method to retrieve the next item. • Other possible features: • Methods that remove an item safely. • Method to “peek” at the next item. • Method to reset the traversal.

  35. Java Iterator Pattern Interfaces • The Java Collections Framework defines two generic interfaces for supporting the iterable design pattern • Implemented by the various collection types such as List<E>, Map<E>, Set<E>, etc. • Iterable<E> • Interator<E> iterator() • Iterator<E>

  36. Iterator<E> • booleanhasNext() • Are we at the end of the traversal? • E next() • Get the next item of the traversal. • Throws a runtime exception if no next item. • void remove() • Not supported by all implementations. • Safely removes last item retrieved by next() from the underlying collection.

  37. Static Class Fields • Indicated by static modifier to field declaration. • Can be accessed via the class name • access modifiers can also be used to control visibility • Contrast with instance fields • Each object has its own copy of an instance field • Value of the instance fields are the state of the object • Only one copy of the class field • Associated with the class as a whole • Common uses • As named constant values associated with the class • In this case, modify the declaration of the field with the keyword final • By convention, named constants are ALL_CAPS • As collective information associated with the class as a whole. • Avoid accessing static class fields through an object. • It does work, but it is misleading and not good style • lec8.ex1

  38. Static Class Methods • Methods associated with the class but that are not associated with a specific object. • No this reference within the function. • Common uses • Getters / Setters for static class fields • Helper / auxiliary functions • Factory methods for creating new instances • We’ll revisit this in more detail later later in the class. • lec8.ex2

  39. Motivating Enumerations • Often need to model part of an object as one value from a set of finite choices • Examples: • Suite of a playing card • Day of week • Directions of a compass • One approach is to use named constants • lec8.ex3 • Drawbacks of this approach • No type safety • No value safety

  40. Simple Java Enumerations • General syntax: access_typeenumEnumName {symbol, symbol, ...}; • Example: • public enum Genre {POP, RAP, JAZZ, INDIE, CLASSICAL} • Enumeration name acts as the data type for the enumerated values. • Enumerated values available as EnumName.symbol as in: Genre.POP • Outside of the class • Fully qualified name required as in: Song.Genre.POP • Symbol names don’t have to all caps, but that is traditional • lec8.ex4

  41. Recap of Interfaces • A “contract” for behavior. • Defined by a set of method signatures. • Acts as a data type. • No implementation. • Specific classes implement the interface

  42. Is-A and casting • A class that implements an interface creates an “is-a” relationship between class data type and the interface data type. • A implements B => A “is a” B • Song is a Media • Video is a Media • Casting allowed across an is-a relationship. Song s = new Song(); Media m; m = (Media) s; Video v = new Video(); Media m; m = (Media) v; Video v = new Video(); Song s; s = (Song) v;

  43. Inheritance • What is inheritance in real life? • Characteristics / resources that you receive from your parents • Get these automatically. • Part of who you are. • Similar idea in object-oriented programming. • In Java, concept of inheritance applied to both interfaces and classes. • Both signaled by the keyword “extends” • Similar in concept, but details are distinctly different. • Class inheritance more complex.

  44. Extending Interfaces • Adds methods to contract. • Original: • parent interface, super interface • New: • subinterface, child interface, extended interface • Created by using the “extends” keyword. public interface CompressedMedia extends Media { intgetCompressedSize(); intgetUncompressedSize(); Media uncompress(); }

  45. Extension Creates Hierarchy Media • Is-A relationship is transitive up the hierarchy. extends Compressed Media Methods for both must be provided. public class Song implements CompressedMedia { ... Song s = new Song(); CompressedMedia cm = (CompressedMedia) s; Media m = (Media) s; Song s2 = (Song) m; OK because s “is a” Compressed Media OK because s is a Media by virtue of extension. Casting from interface back to specific object type is allowed, but at runtime, if the object’s type does not actually match, a runtime exception will be thrown.

  46. Subinterfacing Odds and Ends • Multiple inheritance for interfaces is allowed. • A subinterface can extend more than one existing interface. • In this case, just a union of all methods declared in all of the parent interfaces. • Plus, of course, the ones added by the subinterfaces. • Interfaces can define enumerations.

  47. Extending Classes • Declared with “extends” keyword • Original class • Parent, parent class, superclass • New class • Child, child class, subclass, extended class • Subclasses inherit fields and methods from the parent class. • Collect the common implementation details from related classes into a single parent class. • Define each related class as a subclass that just adds the details that are not in common.

  48. Subinterface vs. Subclass • Extending interface only added behavior to contract. • Since interfaces don’t specify (and don’t care) how contract is fulfilled. • Extending class creates a new class that shares internal implementation details of its super class. COMP 401 :: Spring 2012

  49. Is-A Relationships for Subclasses • Like interfaces, “is a” relationship is transitive up the subclass hierarchy. • A MountainBike object “is a” Bicycle • Because you inherit everything your parent provides, by definition you also implement any interfaces your parent implements. • And so on all the way up the hierarchy. COMP 401 :: Spring 2012

  50. Object • All classes inherit from Object • Top of the class hierarchy. • Since every class must inherit from Object, don’t actually need to specify it. So when we say this: We were implicitly doing this: public class MyClass { ... } public class MyClass extends Object { ... } COMP 401 :: Spring 2012