1CMSC 132: Object-Oriented Programming IIObject-Oriented Programming & Java Language ConstructsDepartment of Computer ScienceUniversity of Maryland, College Park2OverviewObject-oriented programming (OOP)Introduction to OOP principlesJava programming languageReview language constructsIntroduce new language constructsMany from Java 5.03Object-Oriented Programming (OOP)Approach to improving softwareView software as a collection of objects (entities)Motivated by software engineering concernsTo be discussed later in the semesterOOP takes advantage of two techniquesAbstractionEncapsulation4Techniques – AbstractionAbstractionProvide high-level model of activity or dataProcedural abstractionSpecify what actions should be performedHide algorithmsData abstractionSpecify data objects for problemHide representation5Techniques – EncapsulationEncapsulationConfine information so it is only visible / accessible through an associated external interfaceApproachFor some entity X in programAbstract data in XAbstract actions on data in XCollect data & actions on X in same locationProtects and hides XExtension of abstraction6Abstraction & Encapsulation ExampleAbstraction of a RosterDataList of student namesActionsCreate rosterAdd studentRemove studentPrint rosterEncapsulationOnly these actions can access names in rosterROSTERList of namescreate( )addStudent( )removeStudent( )print( )7Java Programming LanguageLanguage constructs designed to support OOPExampleInterface – specifies a contractClass – implements/defines contracts, supports encapsulation of implementationClass libraries designed using OOP principlesExampleJava Collections FrameworkJava Swing8Java InterfaceAn Interface defines a contractCollection ofConstantsAbstract methods; no implementationsCan not be instantiatedClasses can implement interfacesMust implement all methods in interfaceExampleclass Foo implements Bar { … }Similar to abstract classBut class can “inherit” from multiple interfaces9Java Collections FrameworkCollectionObject that groups multiple elements into one unitAlso called container Collection framework consists ofInterfacesAbstract data typeImplementationsReusable data structuresAlgorithmsReusable functionality10OverviewObject-oriented programming (OOP)Introduction to OOP principlesJava programming languageReview language constructsIntroduce new language constructsMany from Java 5.011Review of Java Language ConstructsBasic elementsPrimitive types, variables, constants, operatorsIf-else, switch, while, forClassesObject instancesCreating objects with newObject referencesThe null referenceInstance data, class (static) dataMethodsParameters, return values, polymorphism12Review of Java Language ConstructsInheritanceBase class, derived class, superMethod overriding (vs. overloading)Abstract methodsUp- and down-casting, getClass(), instanceofavoid overuse of these... leads to bad designsInterfaces1D ArraysCreating, indexingExceptionsTry-catch blocks13New Java Language ConstructsAutoboxingEnumerated typesGenericsEnhanced for loopIterator interfaceStream input & outputScanner classAnnotationsBitSet class14Enumerated TypesNew type of variable with set of fixed valuesEstablishes all possible values by listing themSupports values(), valueOf(), name(), compareTo()…Can add fields and methods to enumsExamplepublic enum Color { Black, White } // new enumerationColor myC = Color.Black;for (Color c : Color.values()) System.out.println(c);When to use enumsNatural enumerated types – days of week, phases of the moon, seasonsSets where you know all possible values15Enumerated TypesFrom "Taming the Tiger" presentation by Joshua Bloch and Neal Gafter at Sun's 2004 Worldwide Java Developer Conferencepublic class Card implements Serializable {public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }private final Rank rank;private final Suit suit;private Card( Rank rank, Suit suit ) {this.rank = rank;this.suit = suit;}public Rank rank( ) { return rank; }public Suit suit( ) { return suit; }public String toString( ) { return rank + " of " + suit; }}16Generics – Motivating ExampleProblemUtility classes handle arguments as Objects Objects must be cast back to actual classCasting can only be checked at runtimeExampleclass A { … }class B { … } List myL = new List();myL.add(new A()); // Add an object of type A…B b = (B) myL.get(0); // throws runtime exception// java.lang.ClassCastException17Solution – Generic TypesGeneric typesProvides abstraction over typesCan parameterize classes, interfaces, methods Parameters defined using <X> notationExamplespublic class foo<X, Y, Z> { … }List<String> myNames = ...ImprovesReadability & robustnessUsed in Java Collections Framework18Generics – UsageUsing generic typesSpecify <type parameter> for utility classAutomatically performs castsCan check class at compile timeExampleclass A { … }class B { … } List<A> myL = new List<A>( );myL.add(new A( )); // Add an object of type AA a = myL.get(0); // myL element class A…B b = (B) myL.get(0); // causes compile time error19Generics – IssuesGenerics and subtypingEven if class A extends class BList<A> does not extend List<B>Exampleclass B { … }class A extends B { … } // A is subtype of BB b = new A(); // A used in place of BList<A> aL = new LinkedList<A>();List<B> bL = aL; // compile time errorWhy?20Subtyping and generic typesConsider what could happen if legalclass B { … }class A extends B { … } // A is subtype of BB b = new A(); // A can be used where B expectedList<A> aL = new LinkedList<A>();List<B> bL = aL;bl.add(b);A a = al.getFirst(); // runtime exception21Subtyping and ArraysSubtyping works for arraysclass B { … }class A extends B { … } // A is subtype of BB b = new A(); // A can be used where B expectedA[] aA = new A[1];B[] bA = aA;aA[0] = b; // won't compilebA[0] = b; // get runtime exceptionArguably a mistake22Autoboxing & UnboxingAutomatically convert primitive data typesData value Object (of matching class)Data types & classes convertedBoolean, Byte, Double, Short, Integer, Long, FloatExampleArrayList<Integer> myL = new LinkedList<Integer>();myL.add(1); // previously myL.add(new Integer(1));int y = mL.getFirst(); //previously int y = mL.getFirst().intValue();Also see example in SortValues.java23Comparable Interface Comparablepublic int compareTo(Object o)A.compareTo(B) returnsNegative
View Full Document