1 / 86

Best of Spring 2013

Best of Spring 2013. COMP 401 Spring 2013 Lecture 26 4/25/2013. The Evolution of Programming. As complexity continues to grow… Developing a program as recipe-like sequence of instructions becomes increasingly difficult.

oksana
Download Presentation

Best of Spring 2013

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. Best of Spring 2013 COMP 401 Spring 2013 Lecture 26 4/25/2013

  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 a set of data and a set of functions/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. Fundamental Characteristics of Java • Strongly typed • Variables must be declared with a type specified. • Dichotomy between value types and reference types. • In some OO languages, everything is an object. • Not quite true in Java. • Some basic data types are objects (e.g., String, arrays) • Other basic data types are not (integers, real numbers, booleans) • Garbage collected memory • Memory is automatically allocated when objects are created. • Memory is automatically reclaimed when no possible reference to an object can exist.

  6. 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. • Associated with “methods” and “fields” • Fields are also known as “members”

  7. Method Calls • The terms “method”, “function”, and “procedure” get used almost interchangeably. • There are technical distinctions • Every method in Java is either a “class” method or an “instance” method. • Class methods are declared with the keyword “static” • Can use Java in a non-OO manner by writing your program with only static methods. • This is what A1 asks you to do • Class methods have a slightly different role when used within a program that is written in a OO manner

  8. Calling Methods • Calling a class method: ClassName.methodName(parameters) • Calling an instance method: objectReference.methodName(parameters) • Within the body of a class method or instance method, we can omit the class name or object reference if we are trying to call another class or instance method associated with the same class or instance. methodName(parameters) • Parameters are a comma separated list of values (or expressions) • Must match in number and type according to method’s signature.

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

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

  11. 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 implementation of abstraction to be improved/changed without breaking other code. • Separate “exposed” behavior from “internal” behavior • Exposed behavior • Procedures / functions other objects / code interacts with. • Internal behavior • Procedures / functions defined only for use by methods that are part of the class.

  12. Encapsulation In PracticePart 1: Do Not Expose Internal State • Make all fields private • Amend field declaration with “private” access modifier. • Provide 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.

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

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

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

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

  17. Exposed vs Internal Behavior • Exposed behavior should be reflected in the interface(s) that a class implements • Recall that any method declared in 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

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

  19. 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. • lec5.v01

  20. 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. • lec5.v02

  21. 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 • lec5.v03

  22. 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.v04, lec5.v05

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

  24. 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 • lec5.v08 • Drawbacks of this approach • No type safety • No value safety

  25. Array Basics • Ordered sequence of elements • Elements must be of the same type • Fixed size once created • Valid indices from 0 to length-1 • Arrays are reference types • Have fields and methods like other object types • In particular, size of array is available through length field • Declaring variables that can hold an array reference • type[] variable_name

  26. Arrays as Reference Types • Same reference, same array • Saw this a little bit in lec6.v1 • 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 • Equivalent to array copy code example in lec6.v2 • lec6.v3

  27. 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. } COMP 401 :: Spring 2012

  28. Iterator Design Pattern • Iterator object encapsulates details of item traversal. • Understands details of the underlying collection. • Manages order of items • May want a traversal that is not just first to last. • Underlying collection may not be linear. • Manages state of traversal • Allows traversal to be picked up again later. • Assumption: underlying collection is not changed or modified while the traversal is occurring. COMP 401 :: Spring 2012

  29. Iterator Design Pattern • Iterator object encapsulates details of item traversal. • Understands details of the underlying collection. • Manages order of items • May want a traversal that is not just first to last. • Underlying collection may not be linear. • Manages state of traversal • Allows traversal to be picked up again later. • Assumption: underlying collection is not changed or modified while the traversal is occurring. COMP 401 :: Spring 2012

  30. lec7.v1.Main4 • Java provides “syntactic sugar” for common use of iterators. • Supposing e_coll is Iterable<E>, then these are equivalent: Iterator<E> iter = e_coll.iterator(); while (iter.hasNext()) { E elem = iter.next(); // Do something with element } for (E elem : e_coll) { // Do something with elem }

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

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

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

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

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

  36. Extension vs. Composition • Interface extension appropriate when additional methods make no sense without methods of the parent interface • Alternatively, can compose multiple interfaces together as facets of an object.

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

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

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

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

  41. Instance Fields • Subclass has direct access to public and protected instance fields. • Public: Everyone has access • Generally not a good idea. • Breaks encapsulation. • Private: Only class has access • Generally recommended as default. • Subclasses, however, also shut out. • Protected: Class and subclasses have access. • Like private (i.e., appropriate use of encapsulation) but allows for subclassing(even if outside of package) • lec9.v4 COMP 401 :: Spring 2012

  42. Access Modifier Chart

  43. Subclass Method Polymorphism • Subclass can overload methods in superclass. • Remember, overloading is providing a different version of an existing method. • An example of polymorphism • Method signature is different in some way. • lec10.v1

  44. Overriding Methods • A subclass can “override” a super class method by providing its own definition. • Method signature must be the same. • Original method is visible from subclass • i.e., public, protected, or package-level access • lec10.v2

  45. Class Polymorphism • Previously introduced the idea of “is-a” relationships • Between a class and interfaces implemented. • Between a class and its superclass hierarchy. • This is also an example of polymorphism • Covariance • Treating an instance of a subclass as a reference typed as the parent class. • This can be typed checked at compile type. • Contravariance • Treating a reference typed as the parent class as an instance of a subclass. • Contravariance can not be type checked in advance at compile time. • Fails if the object is actually “invariant” with respect to the subclass. • lec10.v4, lec10.v4main • Also demonstrates protected base class constructor

  46. Virtual Methods • Different OOP languages choose to solve this problem in different ways. • C++, C# • Default is non-virtual solution. • Programmer can force virtual solution by marking a method with a special “virtual” keyword • Java • Methods are always virtual. • No special keyword needed. • lec10.v5

  47. A virtual problem • Drawback to the “always virtual” approach. • Consider the situation in which a subclass just needs a method to “do just a little more”. • In other words, wants to execute a method as defined in the superclass and then tweak the result. • Or maybe do something in advance of executing a method as defined in the superclass. • Because methods are always virtual, casting this reference to superclass in order to get to method as defined by the superclass won’t work. • lec10.v6

  48. It’s a bird, it’s a plane, it’s… • … the super keyword. • The super keyword provides exactly this ability to invoke methods on an instance as it is understood at the superclass. • Note: Not limited to just the overridden method. • lec10.v7

  49. Whence inheritance • Related classes with common internals • Note, not just common behavior • Specialization after the fact of existing classes

  50. Inheritance Recap • Subinterfacing • Adding methods to create a new “contract” • Subclassing • Inherits fields and methods from parent class • Visibility controlled by access modifier • Adds subclass specific fields and methods • Constructor relationship • Overloading parent methods • Subclass methods with different signatures • Overriding parent methods • Subclass methods with same signature • Always virtual • super keyword provides a mechanism to call parent class version of a method

More Related