• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Oops Concept Java
 

Oops Concept Java

on

  • 1,281 views

 

Statistics

Views

Total Views
1,281
Views on SlideShare
1,281
Embed Views
0

Actions

Likes
0
Downloads
27
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Consider P.translate(3,3) vs. P2.translate(3,3) In both cases we are moving a Polygon 3 over and 3 down – the difference is which Polygon is being moved
  • Demonstrate propagation on board
  • We can’t write a method that can sort “anything”, but we can write a method that can sort any Comparable objects – note the use of the interface here
  • See text for finding minimum value of an array. Note that sorting here is simply finding the minimum value and then swapping over and over – but considering a smaller array each time
  • Grocery List, Movie List, Buddy List, To-Do List, Team Roster, Course Roster, Venue List, Guest List, Group List

Oops Concept Java Oops Concept Java Presentation Transcript

  • Object-Oriented ProgrammingConcepts in JavaKamlesh Kumar SinghNibble MATRIX
  • Intro. to Object-OrientedProgramming (OOP)• Object-Oriented Programming consists of3 primary ideas:– Data Abstraction and Encapsulation• Operations on the data are considered to be partof the data type• We can understand and use a data type withoutknowing all of its implementation details– Neither how the data is represented nor how theoperations are implemented– We just need to know the interface (or method headers)– how to “communicate” with the object– Compare to functional abstraction with methods• We discussed this somewhat already and will doso more in Chapter 4
  • Intro. to OOP– Inheritance• Properties of a data type can be passed down to a sub-type– we can build new types from old ones• We can build class hierarchies with many levels ofinheritance• We will discuss this more in Chapter 8– Polymorphism• Operations used with a variable are based on the class ofthe object being accessed, not the class of the variable• Parent type and sub-type objects can be accessed in aconsistent way• We will discuss this more in Chapter 9
  • Objects and Data Abstraction• Consider primitive types– Each variable represents a single, simple datavalue– Any operations that we perform on the dataare external to that dataX + YX 10Y 5+
  • Objects and Data Abstraction• Consider the data– In many applications, data is more complicatedthan just a simple value– Ex: A Polygon – a sequence of connectedpoints• The data here are actually:– int [] xpoints – an array of x-coordinates– int [] ypoints – an array of y-coordinates– int npoints – the number of points actually in the Polygon• Note that individually the data are just ints– However, together they make up a Polygon• This is fundamental to object-oriented programming(OOP)
  • Objects and Data Abstraction• Consider the operations– Now consider operations that a Polygon cando• Note how that is stated – we are seeing what aPolygon CAN DO rather than WHAT CAN BEDONE to it• This is another fundamental idea of OOP – objectsare ACTIVE rather than PASSIVE• Ex:– void addPoint(int x, int y) – add a new point to Polygon– boolean contains(double x, double y) – is point (x,y)within the boundaries of the Polygon– void translate(int deltaX, int deltaY) – move all points inthe Polygon by deltaX and deltaY
  • Objects and Data Abstraction– These operations are actually (logically)PART of the Polygon itselfint [] theXs = {0, 4, 4};int [] theYs = {0, 0, 2};int num = 2;Polygon P = new Polygon(theXs, theYs, num);P.addPoint(0, 2);if (P.contains(2, 1))System.out.println(“Inside P”);elseSystem.out.println(“Outside P”);P.translate(2, 3);• We are not passing the Polygon as an argument,we are calling the methods FROM the Polygon
  • Objects and Data Abstraction– Objects enable us to combine the data andoperations of a type together into a singleentityPxpoints [0,4,4,0]ypoints [0,0,2,2]npoints 4addPoint()contains()translate()Thus, the operationsare always implicitlyacting on theobject’s dataEx: translate meanstranslate the pointsthat make up P
  • Objects and Data Abstraction– For multiple objects of the same class, theoperations act on the object specifiedint [] moreXs = {8, 11, 8};int [] moreYs = {0, 2, 4};Polygon P2 = new Polygon(moreXs, moreYs, 3);Pxpoints [0,4,4,0]ypoints [0,0,2,2]npoints 4addPoint()contains()translate()P2xpoints [8,11,8]]ypoints [0,2,4]npoints 3addPoint()contains()translate()
  • Encapsulation and DataAbstraction• Recall that we previously discussed dataabstraction– We do not need to know the implementationdetails of a data type in order to use it• This includes the methods AND the actual datarepresentation of the object– This concept is exemplified through objects• We can think of an object as a container with dataand operations inside– We can see some of the data and some of theoperations, but others are kept hidden from us– The ones we can see give us the functionality of theobjects
  • Encapsulation and DataAbstraction• As long as we know themethod names, paramsand how to use them, wedon’t need to know howthe actual data is stored– Note that I can use aPolygon without knowinghow the data is stored ORhow the methods areimplemented• I know it has points but Idon’t know how they arestored• Data Abstraction!Pxpoints [0,4,4,0]ypoints [0,0,2,2]npoints 4addPoint()contains()translate()
  • Instance Variables• Let’s look again at StringBuffer– Instance Variables• These are the data values within an object– Used to store the object’s information• As we said previously, when using data abstraction wedon’t need to know explicitly what these are in order to usea class• For example, look at the API for StringBuffer– Note that the instance variables are not even shown there• In actuality it is a variable-length array with a counter tokeep track of how many locations are being used and isactually inherited from AbstractStringBuilder– See source in StringBuffer.java and AbstractStringBuilder.java– cool!!!
  • Instance Variables– Many instance variables are declared with thekeyword private• This means that they cannot be directly accessed outside theclass itself• Instance variables are typically declared to be private, basedon the data abstraction that we discussed earlier– Recall that we do not need to know how the data is representedin order to use the type– Therefore why even allow us to see it?• In AbstractStringBuilder the value variable has no keywordmodifier– This makes it private to the package
  • Class Methods vs. InstanceMethods– Recall that methods we discussed beforewere called class methods (or static methods)• These were not associated with any object– Now, however we WILL associate methodswith objects (as shown with Polygon)– These methods are called instance methodsbecause they are associated with individualinstances (or objects) of a classStringBuffer B = new StringBuffer(“this is “);B.append(“really fun stuff!”);System.out.println(B.toString());
  • Class Methods vs. InstanceMethods– Class methods have no implicit data to act on• All data must be passed into them using arguments– Class methods are called using:ClassName.methodName(param list)– Instance methods have implicit data associatedwith an Object• Other data can be passed as arguments, but there isalways an underlying object to act upon– Instance methods are called using:VariableName.methodName(param list)
  • Constructors, Accessors andMutators• Instance methods can be categorized bywhat they are designed to do:– Constructors• These are special instance methods that are calledwhen an object is first created• They are the only methods that do not have areturn value (not even void)• They are typically used to initialize the instancevariables of an objectStringBuffer B = new StringBuffer(“hello there”);B = new StringBuffer(); // default constructorB = new StringBuffer(10); // capacity 10
  • Constructors, Accessors andMutators– Accessors• These methods are used to access the object insome way without changing it• Usually used to get information from it• No special syntax – categorized simply by theireffectStringBuffer B = new StringBuffer(“hello there”);char c = B.charAt(4); // c == ‘o’String S = B.substring(3, 9); // S == “lo the”// note that end index is NOT inclusiveint n = B.length(); // n == 11– These methods give us information about the StringBufferwithout revealing the implementation details
  • Constructors, Accessors andMutators– Mutators• Used to change the object in some way• Since the instance variables are usually private,we use mutators to change the object in aspecified way without needing to know theinstance variablesB.setCharAt(0, ‘j’); // B == “jello there”B.delete(5,6); // B == “jello here”B.insert(6, “is “); // B == “jello is here”;– These methods change the contents or properties of theStringBuffer object– We use accessors and mutators to indirectlyaccess the data, since we don’t have directaccess – see ex12.java
  • Simple Class Example• We can use these ideas to write our ownclasses– Let’s look a VERY simple example:• A circle constricted to an integer radius• IntCircle– Instance variable: private int radius» Cannot directly access it from outside the class– Constructor: take an int argument and initialize a new circlewith the given radius– Accessors:public double area();public double circumference();public String toString();– Mutator:public void setRadius(int newRadius);• See IntCircle.java and ex13.java (note COMMENTS!!!)
  • More on Classes and Objects• Classes– Define the nature and properties of objects• Objects– Instances of classes• Let’s learn more about these bydeveloping another example together• Goal:– Write one or more classes that represent aCD (compact disc)– Write a simple driver program to test it
  • Developing Another Example• Remember the things we need for a class:– Instance variables– Constructors– Accessors– Mutators
  • Developing Another Example– Once we have the basic structure of theclass we can start writing / testing it– A good approach is to do it in a modular,step-by-step way• Ex: Determine some instance variables, aconstructor or two and an accessor to “output” thedata in the class• Write a simple driver program to test thesefeatures– Once a method has been written and tested we don’thave to worry about it anymore!• Add more to the class, testing it with additionalstatements in the driver program– Let’s do this now!
  • Wrappers• Much useful Java functionality relies onclasses / objects– Inheritance (Chapter 8)– Polymorphic access (Chapter 9)– Interfaces (Chapter 6)• Unfortunately, the Java primitive types areNOT classes, and thus cannot be used inthis way– If I make an array of Object or any otherclass, primitive types cannot be stored in it
  • Wrappers– Wrapper classes allow us to get around thisproblem• Wrappers are classes that “wrap” objects aroundprimitive values, thus making them compatible withother Java classes– We cant store an int in an array of Object, but we couldstore an Integer• Each Java primitive type has a correspondingwrapper– Ex: Integer, Float, Double, Boolean• Ex: Integer i, j, k;i = new Integer(20);j = new Integer(40);
  • Wrappers– The wrapper classes alsoprovide extra usefulfunctionality for these types• Ex: Integer.parseInt() is astatic method that enables usto convert from a String into anint• Ex: Character.isLetter() is astatic method that tests if aletter is a character or not– See more in APIintIntegerdoubleDouble
  • Wrappers and Casting– However, arithmetic operations are notdefined for wrapper classes• So if we want to do any “math” with our wrappers,we need to get the underlying primitive values• If we want to keep the wrapper, we then have towrap the result back up• Logically, to do the following:k = i + j;• The actual computation being done isk = new Integer(i.intValue() + j.intValue());– In words: Get the primitive value of each Integer object,add them, then create a new Integer object with theresult
  • Wrappers– In Java 1.4 and before:• Programmer had to do the conversions explicitly– Painful!– In Java 1.5 autoboxing was added• This does the conversion back and forthautomatically• Saves the programmer some keystrokes• However, the work STILL IS DONE, so from anefficiency point of view we are not saving• Should not use unless absolutely needed– We will see more on how wrappers are usefulafter we discuss inheritance, polymorphismand interfaces
  • Intro. to Java Files• So far– Our programs have read input from the keyboard orcommand line arguments and written output to themonitor• This works fine in some situations, but is not sogood in others:– What if we have a large amount of output that weneed to save?– What if we need to initialize a database that is usedin our program?– What if output from one program must be input toanother?
  • Intro. to Java Files• In these situations we need to use files– Most files can be classified into two groups:1) Text Files• Data is a sequence of ASCII characters storedsequentially• Any “larger” data types are still stored ascharacters and must be “built” when they areread in– Ex: Strings are sequences of characters– Ex: ints are also sequences of characters, butinterpreted in a different way» To create an actual int we need to convert thecharacters – this is what the parseInt method in theInteger class does
  • Text Files• Ex: “12345” in a file is simply 5 ASCII characters:49 50 51 52 53• To convert it into an actual int requires processingthe characters:– We know ‘0’ is ASCII 48– So our integer is(49-48)x104+ (50-48)x103+ (51-48)x102+ (52-48)x101+ (53-48)x100– This can be done in a nice efficient way using a simpleloop, and is what the parseInt method does– Let’s do it ourselves to see how it can be done– Any suggestions on how to start?• See MyInteger.java and ex14.java
  • Text Files– Advantage of text files:• Can read them outside of the program by manydifferent editors or programs• Easy to create– Disadvantage of text files:• Must be converted into the desired types as theyare read in (as demonstrated with parseInt)– This takes time to do and slows I/O• Not the most efficient way to store non-String data– Ex: int 12345678 requires 8 bytes in a text file, but onlyneeds 4 bytes in the computer as an int or in a binary file
  • Binary Files2) Binary Files• Data in the file is stored in the same way (or in a“serialized” version) that it is stored in theprogram• We can store arbitrary bytes or we can store“whole” data types, including primitive types (int,double, etc.) and objects (String, any otherSerializable object type)– We will discuss Serializable more later• Advantages:– Since data is already in its binary form, reading andwriting require little if any conversion and is faster thanfor text files– Non-string data can often be stored more efficiently inits binary form than in ASCII form
  • Binary Files• Disadvantage:– Data in the files is not readable except via a specificcomputer program» Ex: A Java object in a file can only be read in by aJava program– There are reasons to use both of these typesof files in various applications
  • File Streams• Recall a Stream is a continuous, orderedsequence of bytes coming into or going out ofour programs• We can create streams to read from or write tofiles• In Java, file access is provided through ahierarchy of file and stream classes– These allow various different access functionalitiesimplemented in a systematic, consistent way– Often we “wrap” streams around others to providemore specific access• Stream wrappers are a similar notion to our primitive typewrappers – in both cases we are wrapping an object aroundother data to increase the functionality of the data– However, in this case the data being “wrapped” is already anobject
  • Input Files• Lets first consider input– We start with a file and wrap an appropriateinput stream object around it– We want to use one or more input streams– Alternatively, we could wrap a Scanneraround a file to read it in as tokens, as we didfor standard input• Lets look at ex15.java
  • Output Files• How about writing text to an output file:– We cant use the Scanner for that, so we need tolook at some other classes• First we create a File object:File theFile = new File("ex12out.txt");– This will not necessarily create a file – it simply associates alogical file with the file name provided• Next we wrap a FileOutputStream around itFileOutputStream fo;fo = new FileOutputStream(theFile);– The above will start writing at the beginning of the file – wecould also open it for appendfo = new FileOutputStream(theFile, true);• At this point we could write to our file– However, FileOutputStream only allows a few primitive writingoperations (see API)
  • Output Files• To increase the writing functionality we can wrapanother stream around it – PrintWriterPrintWriter outFile = new PrintWriter(fo);– This allows us to use print and println for our primitivetypes and object types• We don’t actually need all of the intermediatevariables in all cases:PrintWriter p = new PrintWriter(newFileOutputStream(newFile("ex12out.txt")));– Note that we are still creating 3 objects, but we arewrapping the inner two right away, thereby avoiding theextra variables–See ex16.java
  • Text vs. Binary Files• We discussed previously that numeric datacan often be stored more efficiently inbinary form than in text form• Lets compare the two by writing the samedata (numbers) to a text file and a binaryfile• Since the data is just numbers we can usea DataOutputStream for our output– Allows only simple methods such as writeInt(),writeDouble(), etc
  • Text vs. Binary Files• Let’s try this and then compare the sizes of thebinary and text files– We will generate a number of random ints andrandom doubles– Store each in a text file and in a binary file andcompare sizes at the end• Note that the size of the integer text file depends greatly onthe values of the integers, while the size of the integer binaryfile is independent of the values– If we are storing very small integers, using a text file will actuallysave us space, but for large integers it will cost us space– ex17.java
  • Composition & Inheritance• Sometimes we want to build a new classthat is largely like one we already have– Much of the functionality we need is alreadythere, but some things need to be added orchanged• We can achieve this in object-orientedlanguages using one of two ways– Composition– Inheritance
  • Composition• We include an object of the class whose functionality weneed as a private instance variable in our own classpublic class NewClass{private OldClass oldVar;…– Referred to as a “has a” relationship– NewClass “has an” OldClass instance• We then write methods that wrap around similarmethods of included classpublic int foo(int arg){return oldVar.foo(arg);}• The new class then seems to provide the same functionality as theincluded class• In addition to any new functionality
  • Composition• This is ideal when an object of NewClass isn’tlogically an object of OldClass– Fails the “is a” test• This is scheme is used by the input and outputstream classes of the java.io package– Ex:DataOutputStream out = newDataOutputStream(newFileOutputStream(“file.out”));– ‘out’ stores the passed in FileOutputStream as aninstance variable– A FileOutputStream isn’t necessarily aDataOutputStream, nor is a DataOutputStreamnecessarily a FileOutputStream– Both are still output stream objects, though
  • Inheritance• Alternatively, our NewClass can directly “inherit”the properties of OldClass– Just then need to add the new properties• Eliminates the need to redefine identicalfunctionality in NewClass– The OldClass public interface can be access directlyby the user• Can still augment the inherited interface• Semantically defines a logical relationshipbetween the two objects
  • Inheritance and “is a”– We can understand this better by consideringthe “is a” idea• A subclass object “is a” superclass object• However, some extra instance variables andmethods may have been added and some othermethods may have been changed– Note that “is a” is a one way operation• Subclass “is a” superclass (specific "is a" general)– With modifications / additions• Superclass is NOT a subclass (general not "is a"specific– Missing some properties– Ex: Bird “is a” Animal
  • Inheritance and “is a”– Bird, Human and Fish are all Animals– However, an Animal is not necessarily a Bird,Human or FishAnimalBird Human Fishis ais ais a
  • Extending Classes• Inheritance in Java is implemented byextending a classpublic class NewClass extends OldClass{…– We then continue the definition of NewClassas normal– However, implicit in NewClass are all dataand operations associated with OldClass• Even though we don’t see them in the definition
  • private, public and protected– We already know what public and privatedeclarations mean– The protected declaration is between publicand private• Protected data and methods are directly accessiblein the base class and in any subclasses and in thecurrent package• However, they are not directly accessible anywhereelse– Note that private declarations are STILL PARTof subclasses, but they are not directlyaccessible from the subclass’ point of view• See SuperClass.java, SubClass.java and ex18.java
  • Inheritance Example• As another example– Compare MixedNumber class andMixedNumber2 class– Both utilize the authors RationalNumberclass to do most of the "work"– Both also have the same functionality, butMixedNumber uses composition andMixedNumber2 uses inheritance• Note simplicity of MixedNumber2 methods• Read over the comments carefully!• See RationalNumber.java, MixedNumber.javaand MixedNumber2.java
  • Java Class Hierarchy• In Java, class Object is the base class toall other classes– If we do not explicitly say extends in a newclass definition, it implicitly extends Object– The tree of classes that extend from Objectand all of its subclasses are is called the classhierarchy– All classes eventually lead back up to Object– This will enable consistent access of objectsof different classes, as we shall see shortly
  • Polymorphism• Idea of polymorphism– See internet definition:• On Google type “definition polymorphism” and seethe results– This search works for many CS terms that you may becurious about• http://www.wordiq.com/definition/Polymorphism_%28computer_science%29– Generally, it allows us to mix methods andobjects of different types in a consistent way
  • Method Overloading– This is called ad hoc polymorphism, or methodoverloading• In this case different methods within the same classor in a common hierarchy share the same name buthave different method signatures (name +parameters)public static float max(float a, float b)public static float max(float a, float b, floatc)public static int max(int a, int b)• When a method is called, the call signature ismatched to the correct method version– Note: This is done during program COMPILATION
  • Method Overloading• If an exact signature match is not possible, the onethat is closest via “widening” of the values is used– “Widening” means that values of “smaller” types are castinto values of “larger” types» Ex: int to long int to float float to double– Fewer widenings provides a "closer" match• If two or more versions of the method are possiblewith the same amount of “widening”, the call isambiguous, and a compilation error will result– See ex20.java– Note: This type of polymorphism is notnecessarily object-oriented – can be done innon-object-oriented languages
  • Polymorphism• Subclassing Polymorphism– Sometimes called “true polymorphism”– Consists basically of two ideas:1) Method overriding• A method defined in a superclass is redefined ina subclass with an identical method signature• Since the signatures are identical, rather thanoverloading the method, it is instead overridingthe method– For subclass objects, the definition in the subclassreplaces the version in the superclass
  • Polymorphism2) Dynamic (or late) binding• The code executed for a method call is associated with thecall during run-time• The actual method executed is determined by the type ofthe object, not the type of the reference– Allows superclass and subclass objects to beaccessed in a regular, consistent way• Array or collection of superclass references can be used toaccess a mixture of superclass and subclass objects• This is very useful if we want access collections of mixeddata types (ex: draw different graphical objects using thesame draw() method call for each)
  • Polymorphism• Ex. Each subclass overridesthe move() method in its ownwayAnimal [] A = new Animal[3];A[0] = new Bird();A[1] = new Person();A[2] = new Fish();for (int i = 0; i < A.length; i++)A[i].move();move()move()move()• References are all the same, butobjects are not• Method invoked is that associatedwith the OBJECT, NOT with thereference
  • Object, Method and InstanceVariable Access• When mixing objects of difference classes,some access rules are important to know:– Superclass references can always be used toaccess subclass objects, but NOT vice versaAnimal A = new Bird(); // this is okBird B = new Animal(); // this is an ERROR– Given a reference R of class C, only methods andinstance variables that are defined (initially) in classC or ABOVE in the class hierarchy can be accessedthrough R• They still exist if defined in a subclass, but they are notaccessible through R
  • Object, Method and InstanceVariable Access– Ex:• Suppose class Fish contains a new instancevariable waterType and a new methodgetWaterType()Fish F = new Fish();Animal A = new Fish();System.out.println(F.getWaterType()); // okSystem.out.println(A.getWaterType());– The above is NOT legal, even though the method existsfor class Fish. The reason is that the method is notvisible from the reference’s point of view (A is an Animalreference so it can only “see” the data and methodsdefined in class Animal)System.out.println(((Fish) A).getWaterType());– This is ok, since we have now cast the reference to theFish type, which CAN access the method
  • Object, Method and InstanceVariable Access• Note that we can access these methods orinstance variables INDIRECTLY if an overriddenmethod accesses them– So, for example, if the move() method as defined in classFish called the getWaterType() method, and we calledA.move();– It would work fine– See ex21.java for an example
  • Object Methods• We’ve already seen that every class automaticallyinherits from Object• Class Object defines a set of methods that every classinherits– public String toString()– public boolean equals()– public int hashCode()– protected Object clone() //we’ll ignore this• Each of these forms a contract to which all objects mustadhere• Object has a default implementation for each of thesemethods– Unless our classes override them, they inherit this behavior– May or may not be what our classes require
  • toString()• toString() returns a string representation of theobject• The string “should be a concise but informativerepresentation that is easy for a person to read• RULE: All classes should override this method• Default implementation from the Object classconstructs a string like:ClassName@30E50DA3– Name of the class, ‘@’ character, followed by theHashCode for the class
  • equals()• Indicates whether two objects are logically equal to eachother– Ex. string1.equals(“done”)• Seems simple, but there is some subtlety here• equals() must satisfy the definition of an “equivalencerelation”– Reflexive– Symmetric– Transitive• Default implementation from the Object class isequivalent to ‘==‘– For any two references, x and y:x.equals(y) is true if and only if x == y– The references must point to the same object for equals() toreturn true
  • Contract of equals()• equals() must be:– Reflexive: for any non-null reference variable, x:x.equals(x) must be true– Symmetric: for any two non-null reference variables, x and y:If x.equals(y) is true, then y.equals(x) must be true– Transitive: for any non-null reference variables, x, y, and z:If x.equals(y) is true and y.equals(z) is true, thenx.equals(z) must be true– Consistent: for any two non-null references, x and y, mutliplecalls to x.equals(y) must consistently return true orconsistently return false unless the data stored in either x or ychanges between calls to equals().– Safe: for non-null reference x and null reference y:x.equals(y) must return falsei.e. x.equals(null) must return false• equals() should not generate a NullPointerException, orClassCastException
  • Contract of equals()• Consider a class SubClass– Extends SuperClass• Has the following equals() methodpublic boolean equals(Object o){SubClass sub = (SubClass) o;return (name.equals(sub.name) &&type.equals(sub.type));}• What’s wrong with this?– Object o could be null– Need to checkif(o == null) return false;
  • Contract of equals()• Now consider the super class, SuperClass– Has it’s own equals methodpublic boolean equals(Object o){if(o == null) return false;SuperClass sup = (SuperClass) o;return name.equals(sup.name);}• What’s wrong here?– Object o may be an instance of SubClass– The cast will succeed, though, since SubClass extendsSuperClass– What about symmetry: o.equals(this) won’t return true• ClassCastException will result– In general, an instance cannot be equal to any instance of asubclass• This may be desirable in some cases• Extremely difficult to maintain a working ‘contract of equals()’
  • Template for equals()• For any class, the general form of the equals() method should be:public class MyClass{public boolean equals(Object o){if(o == null) return false;if(o instanceof MyClass){MyClass my = (MyClass) o;//perform comparison}return false;}}
  • hashCode()• Returns a integer index value for the object– Used by hashtables to store objects• Contract– Multiple calls to hashCode() during one execution ofthe program must return the same integer• Assuming no data contained in the object changes betweencalls– For any two non-null references, x and y:If x.equals(y), then x.hashCode() == y.hashCode()• If they are logically equal, they must have the samehashCode()• If they aren’t equal, it doesn’t matter what the hashCode()returns
  • Composition or Inheritance• Caveats like those we just discussed arise oftenwith Inheritance• Also, In heritance permanently associates asuperclass with our class at compile time– We can only inherit from a single class– Composition allows our class the flexibility to wraparound different superclasses at run-time• Composition is generally preferred overInheritance• We loose polymorphism and dynamic bindingwith Composition though– In many cases, we need those capabilities– We use abstract classes and Interfaces to help solvethese problems
  • Exceptions in Java• Run-time errors happen– User enters incorrect input– Resource is not available (ex. file)– Logic error (bug) that was not fixed• For Production software– Having a program "crash" is a HIGHLYUNDESIRABLE thing• Users think software is no good• Lose confidence
  • Exceptions in Java• Exception:– An occurrence of an erroneous, unusual orunexpected event in a program execution– In older languages• Code the handling of exceptions into each area ofthe program that needed it• Some exceptions could not even be handled bythe HLL– ex. standard Pascal cannot handle I/O errors or divisionby 0» Ask for integer and user enters a text string – whatdo you do?
  • Exceptions in Java– In newer languages• Exception handling built into the language• We can separate exception handling from the"main line" code– Java uses an exception handling modelsimilar to that used in C++Exceptions are objects that arethrown and catchedSome exceptions are built into the languageOthers can be created and thrown by theprogrammer
  • Exceptions in Java• Java exception handling– Exceptions are handled using try-catchblockstry{ // code that will normally execute}catch (ExceptionType1 e){ // code to "handle" this exception}catch (ExceptionType2 e){ // code to "handle" this exception}... // can have many catchesfinally{ // code to "clean up" before leaving try block}
  • Exceptions in Java– If all goes well (no exceptions occur)• Code in try block is executed, followed by code in(optional) finally block– If an exception occurs anywhere in the tryblock• Execution immediately jumps out of the try block• An exception handler is sought in a catch block• If exception is handled in a catch block, that blockexecutes; if not, exception is propagated– Whether exception is handled or propagated,finally block is executed
  • Exceptions in Java– If an exception is handled• Execution resumes immediately AFTER try/catch block inwhich it was handled, and does NOT return to throw point• termination model of exception handling– As opposed to a resumption model, where executionresumes from where the exception occurred– If an exception is propagated• A handler is searched for by backing up through the callchain on the run-time stack• This is dynamic exception propagation• If no handler is ever found– Console applications crash and report exception– GUI applications will continue to execute, but may be in aninconsistent state – more soon
  • Exceptions in Java• Checked vs. Unchecked exceptions– Checked exceptions• If a method does NOT handle these, the methodMUST state that it throws them– Done in a throws clause in the method header• These include IOException, andInterruptedException (and their subclasses)– Unchecked exceptions• Method not required to explicitly "throw" these• These include RunTimeException and Error
  • Exceptions in Java• Catching exceptions– Catching a superclass of an exception willcatch subclass exception objectscatch (Exception e)» "catch all" if no other exceptions match– Should list exceptions in order of mostspecific to most general– If catch above is first NO OTHER catches in the blockcould ever execute– It is better style to be as specific as possiblewith the exceptions that are caught• See ex22.java
  • Abstract Classes• Abstract classes– Sometimes in a class hierarchy, a class may bedefined simply to give cohesion to its subclasses• No objects of that class will ever be defined• But instance data and methods will still be inherited by allsubclasses– This is an abstract class• Keyword abstract used in declaration• One or more methods declared to be abstract and are thusnot implemented• No objects may be instantiated
  • Abstract Classes– Subclasses of an abstract class must implement allabstract methods, or they too must be declared to beabstract– Advantages• Can still use superclass reference to access all subclassobjects in polymorphic way– However, we need to declare the methods we will need in thesuperclass, even if they are abstract• No need to specifically define common data and methods foreach subclass - it is inherited• Helps to organize class hierarchy– See ex23.java– Let’s look at MusicCD and CompilationCD again too
  • Interfaces• Java allows only single inheritance– A new class can be a subclass of only oneparent (super) class– There are several reasons for this, from boththe implementation (i.e. how to do it in thecompiler and interpreter) point of view and theprogrammer (i.e. how to use it effectively) pointof view– However, it is sometimes useful to be able toaccess an object through more than onesuperclass reference
  • Interfaces– We may want to identify an object in multipleways:• One based on its inherent nature (i.e. itsinheritance chain)– Ex: A Person• Others based on what it is capable of doing– Ex: An athlete– Ex: a pilot
  • Interfaces• A Java interface is a named set ofmethods• However, no method bodies are given – just theheaders• Static constants are allowed, but no instancevariables are allowed• No static methods are allowed– Any Java class (no matter what itsinheritance) can implement an interface byimplementing the methods defined in it– A given class can implement any number ofinterfaces
  • Interfaces–Ex:public interface Laughable{public void laugh();}public interface Booable{public void boo();}• Any Java class can implement Laughableby implementing the method laugh()• Any Java class can implement Booable byimplementing the method boo()
  • Interfaces• Ex:public class Comedian implements Laughable, Booable{// various methods here (constructor, etc.)public void laugh(){System.out.println(“Ha ha ha”);}public void boo(){System.out.println(“You stink!”);}}
  • Interfaces– An interface variable can be used toreference any object that implements thatinterface• Note that the same method name (ex: laugh()below) may in fact represent different codesegments in different classes• Also, only the interface methods are accessiblethrough the interface reference– Ex:Laughable L1, L2, L3;L1 = new Comedian();L2 = new SitCom(); // implements LaughableL3 = new Clown(); // implements LaughableL1.laugh(); L2.laugh(); L3.laugh();
  • Interfaces– Polymorphism and Dynamic Binding also apply tointerfaces• the interface acts as a superclass and the implementingclasses implement the actual methods however they want– An interface variable can be used to reference anyobject that implements that interface• However, only the interface methods are accessiblethrough the interface reference– Recall our previous example:Laughable [] funny = new Laughable[3];funny[0] = new Comedian();funny[1] = new SitCom(); // implements Laughablefunny[2] = new Clown(); // implements Laughablefor (int i = 0; i < funny.length; i++)funny[i].laugh();– See ex24.java
  • "Generic" Operations– How does it benefit us to be able to accessobjects through interfaces?• Sometimes we are only concerned about a givenproperty or behavior of a class– The other attributes and methods still exist, but we dontcare about them for what we want to do• For example: Sorting– We can sort a lot of different types of objects» Various numbers» People based on their names alphabetically» Movies based on their titles» Employees based on their salaries– Each of these classes can be very different– However, something about them all allows them to besorted
  • “Generic” Operations– They all can be compared to each other• So we need some method that invokes this comparison– In order to sort them, we dont need to know oraccess anything else about any of the classes• Thus, if they all implement an interface that defines thecomparison, we can sort them all with a single method thatis defined in terms of that interface– Huh? Qué?• Perhaps it will make more sense if we develop anexample…but first we will need some background!
  • Simple Sorting• What does it mean to sort our data?– Consider an array, A of N items:A[0], A[1], A[2], …, A[N-1]– A is sorted in ascending order ifA[i] < A[j] for all i < j– A is sorted in descending order ifA[i] > A[j] for all i < j– Q: What if we want non-decreasing or non-increasingorder?• What does it mean and how do we change the definitions?
  • Simple Sorting• How do we sort?– There are MANY ways of sorting data• Sorting has been widely studied in computer science– Some algorithms are better than others• The most useful measure of “better” here is how long it takesto run• The better algorithms run a lot more quickly than the pooreralgorithms– However, some very simple algorithms are ok if N isnot too large• We will look at a simple algorithm here– In CS 0445 you will see other, better ways of sorting
  • SelectionSort• SelectionSort is very intuitive:– Idea:Find the smallest item and swap it into index 0Find the next smallest item and swap it into index 1Find the next smallest item and swap it into index 2…Find the next smallest item and swap it into index N-2• What about index N-1?– Let’s trace it on the board for the following data:0 1 2 3 4 5 6 735 50 20 40 75 10 15 60
  • SelectionSort– Let’s look at the code• SortInt.java and ex25.java• Note:– Done in a modular way utilizing methods– Trace it on the example from previous slide– Done here in terms of only one type – int• So how can we sort arrays of other types, forexample objects?– We could write a version of SelectionSort for each– Lots of typing, where everything other than the typesinvolved is the same for each one– Is there a better way?
  • Comparable Interface– Consider the Comparable interface:• It contains one method:int compareTo(Object r);• Returns a negative number if the current object is less than r,0 if the current object equals r and a positive number if thecurrent object is greater than r• Look at Comparable in the API• Not has restrictive as equals() – can throwClassCastException– Consider what we need to know to sort data:• is A[i] less than, equal to or greater than A[j]– Thus, we can sort Comparable data withoutknowing anything else about it• Awesome!• Polymorphism allows this to work
  • Using Comparable– Think of the objects we want to sort as “blackboxes”• We know we can compare them because theyimplement Comparable• We don’t know (or need to know) anything elseabout them– Thus, a single sort method will work for anarray of any Comparable class• Let’s write it now, altering the code we alreadyknow from our simple sort method• See Sorting.java and ex26.java– Also see SortingT.java and ex26T.java
  • Binary Search• Consider Sequential Search again– See Procedural Programming slides and ex8.java– Note that in the worst case we look at every item inthe array• We say this is a linear run-time – or time proportional to N,the number of items in the array– Can we do better?• If the data is unsorted, no– It could be any item, so in the worst case we’ll have to try themall• What if we sort the data? Will that help?– Consider example: Guess number from 1-1000
  • Binary Search• Idea of Binary Search:– Searching for a given key, K– Guess middle item, A[mid] in array• If A[mid] == K, we found it and are done• If A[mid] < K then K must be on right side of thearray• If A[mid] > K then K must be on left side of thearray– Either way, we eliminate ~1/2 of the remaining items withone guess– Search for 40 below0 1 2 3 4 5 6 710 15 20 35 40 50 60 75
  • Binary Search• What if item is not in array? We need a stopping condition inthe “not found” case– Think about what is happening with each test• Either we move left index to the right or• We move right index to the left• Eventually they will “cross” – in this case the item is notfound– Idea is there is “nothing left” in the array to search– Search previous array for 25– How to code this? Not difficult!• See authors code: Searching.java, PhoneList2.java– Trace execution
  • Binary Search– So is Binary Search really an improvementover Sequential Search• Each “guess” removes ~½ of the remaining items• Thus the total number of guesses cannot exceedthe number of times we can cut the array in halfuntil we reach 0 items– Ex: 32 16 8 4 2 1 => 6– Generally speaking, for N items in the array, in the worstcase we will do ~log2N guesses– This is MUCH better than Sequential Search, which has~N guesses in the worst case– You will discuss this more in CS 0445 and CS 1501
  • Collections• Sorting and Searching are used often• With Generics, the code only needs written once– Can then be used in any situation– Provided we’re dealing with Comparable objects• Java has predefined these methods for us– Arrays.sort()– Arrays.binarySearch()– Operate on arrays• There are other ways of storing a group of relatedobjects– Offer performance benefits over arrays in some situations– Offer a conceptual implementation of some container• e.g. a Set– Doesn’t contain duplicates– Can Add or Remove objects– Can perform Union, Intersection, Difference operations– An object is either in the Set or it isn’t
  • Collections• Java refers to these as “Collections”– Containers of other data objects– “Collect” related objects into a single object• Provides conceptual view of the container– Consider a File System for example• Directory Tree of Files• Independent of Storage media (Hard Disk, CD, Flash Drive)• Collections are similar– Separate Interface with which we access the stored objects from theImplementation• Used often enough that Java provides standard implementation ofeach type of Collection– Collection• List (Vector)• Set– SortedSet• Queue– Map (Hashtable)• SortedMap– Stack• See Java API
  • List• What is a List?– Let’s consider lists we make in every day life– What kinds are there?– What information does each store?– How can we access and change each?• A List is a sequence of items or objects– A container of them– Implied arbitrary order of the elements– Size shrinks and grows with the number of items in the list– We can access an element if we know its position in the List– We can insert an item to any position– We can remove an item from any position
  • List Implementation• We now have a concept of a List– A scheme by which we store and access elements in the List– This is defined by the List Interface in Java• See Java API• Notice add(), get(), remove(), contains()• Assumes objects have well defined equals() method• This defines the behavior of a List– In order to use a list, though, we need implement it• There are two common concrete implementations– ArrayList• Uses a private array to store and order the elements– LinkedList• Uses a chain of nodes, each of which stores a single item• When to use each requires knowledge of theimplementation
  • ArrayList• We use an array to store the items in the List– Arrays have a fixed size– List has an arbitrary size– If our list has n elements, we need an array of size n or MORE• We can leave extra empty spaces to store elements added later• We can resize the array if we need more space• List needs to maintain an order to the elements– Array does this for us• But consider– Inserting or adding an element• Need free the index where the element is to be stored• Need to keep maintain the same order with the new element added• Requires shifting some elements to higher indices– Removing an element• Array now has an unused index• Have to shift elements to lower indices to keep ordering– A lot of shifting!!!• NOTE: The Vector class provides the same implementation, butprovides synchronization for multithreaded applications (slower)
  • LinkedList• The strict array indexing causes this need for shifting– Can we avoid this?• Consider this classpublic class Node{private Object value;private Node next;…}• Each Node contains a reference to another Node– Forms a chain of Nodes• If we keep a reference to the first Node, we can access any of themby repeatedly accessing the ‘next’ reference– Show on board– Getting element at position I requires us to traverse the chain• Disadvantage over an array• Consider adding, and removing elements again
  • Which and How to Use• ArrayList when– Add and remove mostly from end of list– Perform a lot of additions• LinkedList when– Frequent additions and removals at arbitrarypositions, especially beginning• This is discussed further in CS 0445• We want to hide the implementation of acollection as much as possible– We only care that we have List– List Interface provides this abstraction– See ex27.java
  • Set• Similar to a List except– No order to the elements– Cannot contain duplicate objects• A Set is a collection of objects that cannot contain duplicates– No two objects o1 and o2 in a Set can exist such that o1.equals(o2)is true– Care must be taken when storing mutable objects• Cannot change data in an object that makes o1.equals(o2) true afterthey’ve been added to the Set• Operations on a Set– Add an element – add()– Remove an element – remove()– Test for inclusion – contains()– Union (combine elements from two Sets) – addAll()– Intersection (keep elements two Sets have in common) – retainAll()– Difference (keep elements not found in a second Set) – removeAll()• Implementations– HashSet stores elements in a “Hashtable”– LinkedHashSet: similar to HashSet– TreeSet stores elements in a Binary Tree
  • HashSet• Imagine implementing a Set with an array– To maintain the constraint that the Set doesn’t contain duplicates, we’dhave to do something like:for(int i = 0; i < count; i++)if(array[i].equals(newElement))return; //don’t add new elementarray[count++] = newElement;– We have to check each item before knowing if a duplicate existed in thearray• What if we could know the index where a duplicate would be storedif it was in the Set?– Just check the element(s) at that index with equals()– Add the new Element if not there• This is how a Hashtable works– Uses newElement.hashCode() to find index• Notice the need for the contract of equals() and hashCode()– Why?
  • Iterators• We’ve seen two types of Collections so far– List– Set• Recall how often we’ve used the following code witharraysfor(int i = 0; i < array.length; i++){…}– Loop “for each” element of the array– Use variable ‘i’ to keep track of position in the array• This is a common and needed operation for anyCollection– How do we do this when a Collection has no implied order?– How do we do this in a common way for any type of Collection?• An Iterator is a object that can traverse over and provideaccess to each element– User doesn’t know how it finds the next element
  • Using Iterators• Iterator class defines two methods– hasNext()• returns true if there is another element to examine– next()• returns the current element as an Object• Prepares the iterator to return the next element• Loop then looks like:for(Iterator i=collect.iterator(); i.hasNext();){MyClass item = (MyClass) i.next();…//Process the item}• Java provides a shorthand version of this, called “foreach” loop:for(Object o : collect){MyClass item = (MyClass) o;… // Process the item}– No need to explicitly declare an Iterator– “collect” variable must be an instance of a class that implements Iterableinterface• See ex28.java
  • Order in Sets• The HashSet Class is the simplest implementation ofthe Set interface– Iterator can return the elements in any particular order– Can be chaotic• It can be advantageous to ensure an Iterator returns theelements is some consistent order• Two implementations of the Set Interface do this– LinkedHashSet• Like HashSet• Iterator returns elements in the order in which they were added tothe Set– TreeSet• Iterator returns elements in sorted order• Requires stored objects to be Comparable• Elements actually stored in sorted order in a binary tree• See ex28b.java
  • Queue• We often don’t need to be able to modify all a Collection’s elements– Can even be advantageous to prevent access to every element– Force modification of the Collection according to specific rules• A queue is an ordered collection of objects that:– Allows new items to be added only to the end– Allows items to be removed only from the front– Similar to a waiting line– First item added to the end is the first item removed from the front (FIFOordering – First In, First Out)– No other item can be removed until the first item is removed• Implementation– How could we implement a Queue?– An array could impose the needed ordering• Would require a lot of shifting• Circular array is still cumbersome– LinkedList class also implements the Queue interface• Ideal for a Queue• Why?• See ex28c.java
  • Stack• Consider a stack of plates on a spring in a bin ina cafeteria– When a plate is added, spring compresses, hiding allplates below– Only plate that can be removed is the top plate• The last one that was added– This is the behavior of a Stack• A Stack is a data structure where objects canonly be added to or removed from the top– Last item added is the first to be removed– LIFO ordering – Last In, First Out
  • Stack Implementation• How would this best be implemented?– Array– Linked list• Either would be efficient• Array doesn’t require the extra storage of saving areference to each object• java.util.Stack is a concrete class– Can create instances of it– Ex:Collection collection = new Stack();Stack stack = new Stack();• See ex28d.java
  • Map• The Map Interface differs from a Collection• Defines a mapping from one set of objects to another– Like a function in Mathematics: y = f(x)– Given an object, x, the map returns an object, y– Refer to x as the key• An array fits this description– Maps an int to an object stored in the array– Each int uniquely identifies and is associated with one of theobjects• A Map allows us to impose a logical relationshipbetween an object and its index (key)– Ex:• The title a CD could be the index of our AbstractCD class• A Person’s name could index their phone number (Phone Book)
  • Map Implementation• Recall our discussion of a Set– Used hashCode() to store object in array– Used compareTo() to order object in tree• We now have two objects– One is the key for other– Use hashCode() of key to find location to store the other object– Use compareTo() of key to order second object in a binary tree– Indexing object then needs to have well defined equals(),hashCode(), and compareTo()– Stored object doesn’t have to be as strictly implemented• Analogous Map Implementations to Set– HashMap– LinkedHashMap– TreeMap• Implements SortedMap Interface• See ex29.java
  • Iterating over a Map• A Map is a complex data structure– Keys– Values• The keySet() method returns a Set containing all thekeys stored in the Map– Map cannot contain duplicate keys– Iterate over this Set• The values() method returns a Collection of allobjects that have an associated key– May contain duplicate objects– Iterate over this collection• The entrySet() method returns a Set of all the (key,value) pairs– Each object in the Set is of the type Map.Entry– Iterate over this Set
  • Generics• From the previous slides– Each collection or Iterator returns an Object– Necessary since it is designed to work for any kind of object– Requires us to cast the reference to an instance that we need– Ex:List list = new LinkedList();list.add(“Some Pig”);String s = (String) list.get(0);String t = (String) list.iterator().next();• The cast can be annoy• The list may also not really contain Strings• We’d like to force the List to only contain specific types– We wouldn’t need the cast– We could be sure what type of objects the List contained• This is where “Generics” works well
  • Generics• We “parameterize” the instance of our List withthe type of object we expect it to contain usingthe <> syntax– ExList<String> list = newLinkedList<String>();list.add(“Some Pig”);String s = list.get(0);String t = list.iterator().next();– Declares a “List of Strings” instead of a simple List– Compiler can now ensure only Strings are added tothis particular list– We no longer need the casts
  • Writing a Generic Class• Use the <> syntax in the class defintionpublic interface List<E>{void add(E x);}• This is similar to declaring parameters in amethod– Called Formal Type Parameters• The <E> declares that a type must be usedwhen an instance is created– The type is then used in place of anywhere the ‘E’ isused in the class definition• e.g. add(E x);
  • Subtyping with Generics• Consider the following code:List<String> listS = newArrayList<String>();List<Object> listO = listS;• Is this legal?– A String is an Object– A list of Strings is a list of Objects• What if we call: listO.add(new Object());– We’ve added something to the list that isn’t a String– Compiler thinks it’s a List of Object, though– Can’t allow assignment statement• If class Foo extends Bar, List<Foo> is not a List<Bar>– This is kind of restrictive
  • Wildcards in Generics• Ex: In ex28, we had the method:public void printCollection(Collection c) {for(Object o : c)System.out.println(o);}• To Parameterize this code, we might try:public void printCollection(Collection<Object> c) {for(Object o : c)System.out.println(o);}• With the subtype restriction, we can’t passanything other than List<Object>– Not very helpful– We can handle any type of List, though• Use Wildcard, ?, in this situation
  • Wildcards in Generics• Ex:public void printCollection(Collection<?> c){for(Object o : c)System.out.println(o);}• Call this a “Collection of unknown type”– Any type of Collection can now match this– Can iterate with type Object• Any type can be cast to Object – this is safe• This lets read from the Collection but not modify– e.g. c.add(new Object()); will fail to compile– Not sure of the actual type of the Collection• See ex30.java
  • Bounded Wildcards• Recall our Animal, Fish, Bird, Person classes• We’d like to write a method like:public void printAnimals(Collection<Animal> c) {for(Animal a : c) {a.characteristics();a.move();}}• This can then only accept a Collection of Animal• If we use a wildcard (‘?’), we lose access to themove() and characteristics() methods
  • Bounded Wildcards• The solution is a bounded wildcard:printAnimals(Collection<? extends Animal> c) {for(Animal a : c) {a.characteristics();a.move();}}• Stated as a “Collection of any subtype of Animal”– Can pass a List of Person• Know that the objects in the Collection are at leastAnimals– Iterator can then be a reference to Animal– Polymorphism will call the appropriate instance method• Unable to add any new objects to the Collection• See ex31.java
  • Bounded Wildcards• The ‘? extends MyClass’ syntax defines anupper bound• Likewise, ‘? super MyClass’ can define alower bound– Means any class that is a superclass of class T– E.g. Comparable<? super T>• Dealing with a comparable object that can compare itself withany superclass of T• See next example
  • Generic Methods• Suppose we want to write a method copies an array into aCollection:public void fromAtoC(Object[] a, Collection<?> c) {for(Object o : a)c.add(o);}• We’ve already learned that we can’t do this with the wildcard• We can use generic methodspublic <T> void fromAtoC(T[] a, Collection<T> c) {for(T o : a)c.add(o);}• All the same wildcard rules applypublic <T> listCopy(List<? extends T> source,List<T> dest){}• When to use:– Notice the dependency between the types in the parameters– If the dependency does not exist, you should use wildcards instead– Also used if the return type of the method is type dependent• See again SortingT.java, ex26T.java, and also ex32