Object-Oriented Programming II: Java Language Constructs and Abstraction Techniques - Prof, Study notes of Computer Science

An overview of object-oriented programming (oop) principles and java programming language constructs. It covers the concepts of abstraction and encapsulation, and introduces new java language constructs such as interfaces, generics, and enumerated types. The document also mentions the java collections framework and java swing as examples of class libraries designed using oop principles.

Typology: Study notes

Pre 2010

Uploaded on 02/13/2009

koofers-user-8fx
koofers-user-8fx ๐Ÿ‡บ๐Ÿ‡ธ

10 documents

1 / 18

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CMSC 132:
Object-Oriented Programming II
Object-Oriented
Programming & Java
Language Constructs
Department of Computer Science
University of Maryland, College Park
Overview
Object-oriented programming (OOP)
Introduction to OOP principles
Java programming language
Review language constructs
Introduce new language constructs
Many from Java 5.0
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download Object-Oriented Programming II: Java Language Constructs and Abstraction Techniques - Prof and more Study notes Computer Science in PDF only on Docsity!

CMSC 132:

Object-Oriented Programming II

Object-Oriented

Programming & Java

Language Constructs

Department of Computer Science

University of Maryland, College Park

Overview

Object-oriented programming (OOP)

Introduction to OOP principles

Java programming language

Review language constructs Introduce new language constructs Many from Java 5.

Object-Oriented Programming (OOP)

Approach to improving software

View software as a collection of objects (entities)

Motivated by software engineering concerns

To be discussed later in the semester

OOP takes advantage of two techniques

  1. Abstraction
  2. Encapsulation

Techniques โ€“ Abstraction

Abstraction

Provide high-level model of activity or data

Procedural abstraction

Specify what actions should be performed Hide algorithms

Data abstraction

Specify data objects for problem Hide representation

Java Programming Language

Language constructs designed to support OOP

Example Interface โ€“ supports procedure abstraction Class โ€“ supports encapsulation

Class libraries designed using OOP principles

Example Java Collections Framework Java Swing

Java Interface

Interface

Collection of Constants Abstract methods Can not be instantiated

Classes can implement interface

Must implement all methods in interface Example class foo implements bar { โ€ฆ } // interface bar

Similar to abstract class

But class can โ€œinheritโ€ from multiple interfaces

Java Collections Framework

Collection

Object that groups multiple elements into one unit Also called container

Collection framework consists of

Interfaces Abstract data type Implementations Reusable data structures Algorithms Reusable functionality

Overview

Object-oriented programming (OOP)

Introduction to OOP principles

Java programming language

Review language constructs Introduce new language constructs Many from Java 5.

New Java Language Constructs

Autoboxing

Enumerated types

Generics

Enhanced for loop

Iterator interface

Stream input & output

Scanner class

Annotations

BitSet class

Autoboxing & Unboxing

Automatically convert primitive data types

Data value โ‡” Object (of matching class) Data types & classes converted Boolean, Byte, Double, Short, Integer, Long, Float

Example

ArrayList myL = new ArrayList(); myL.add(1); // previously myL.add(new Integer(1)); Integer X = new Integer(2); int y = X; // previously int y = X.intValue();

Also see example in SortValues.java

Enumerated Types

New type of variable with set of fixed values Establishes all possible values by listing them Supports values(), valueOf(), name(), compareTo()โ€ฆ Can add fields and methods to enums Example public enum Color { Black, White } // new enumeration Color myC = Color.Black; for (Color c : Color.values()) System.out.println(c); When to use enums Natural enumerated types โ€“ days of week, phases of the moon, seasons Sets where you know all possible values

Enumerated Types

From "Taming the Tiger" presentation by Joshua Bloch and Neal Gafter at Sun's 2004 Worldwide Java Developer Conference public 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; } }

Generics โ€“ Usage

Using generic types

Specify for utility class Automatically performs casts Can check class at compile time

Example

class A { โ€ฆ } class B { โ€ฆ } List myL = new List( ); myL.add(new A( )); // Add an object of type A A a = myL.get(0); // myL element โ‡’ class A โ€ฆ B b = (B) myL.get(0); // causes compile time error

Generics โ€“ Issues

Generics and subtyping

Even if class A extends class B List does not extend List

Example

class B { โ€ฆ } class A extends B { โ€ฆ } // A is subtype of B B b = new A(); // A used in place of B List myL = new List(); // compile time error // List used in place of List // List is not subtype of List

Comparable Interface

Comparable

public int compareTo(Object o) A.compareTo(B) returns Negative if A < B, 0 if A = B, positive if A > B

Properties

Imposes total ordering on objects of a class Referred to as the class's natural ordering Can sort using Collections.sort( ) & Arrays.sort( ) Example: Collections.sort(myList); Can use as keys in SortedMap & SortedSet

Comparator Interface

Comparator

public int compare(Object A, Object B) Negative if A < B, 0 if A = B, positive if A > B

Properties

Imposes total ordering on objects of a class Provide alternatives to natural ordering Supports generics Example: class myC implements Comparator{ โ€ฆ } Use as parameter for sort function Example: Collections.sort(myFooList, new myC( ) );

Enhanced For Loop

Works for arrays and any class that

implements the Iterable interface

Has method iterator( ) returns Iterator object

For loop handles Iterator automatically

Test hasNext( ), then get & cast next( )

Example 1 // Iterating over a String array

String[ ] roster = {"John", "Mary", "โ€œAlice", "Mark"}; for (String student : roster) System.out.println(student);

Enhanced For Loop

Example 2

ArrayList roster = new ArrayList( ); roster.add("John"); roster.add("Mary"); Iterator it = roster.iterator( ); // using an iterator while (it.hasNext( )) System.out.println(it.next( )); for (String student : roster) // using for loop System.out.println(student);

Stream Input/Output

Stream

A connection carrying a sequence of data (ordered sequence of bytes)

Streams can be associated with

Files, memory, other Strings

Many Java classes for handling streams

Data consisting of characters (e.g., text files) Data consisting of raw bytes (e.g., binary files) Can buffer information

Combining different classes

Can define stream with desired characteristics

Using Streams

Opening a stream

Connects program to external data Location of stream specified at opening Only need to refer to stream

Usage

  1. import java.io.* ;
  2. Open stream connection
  3. Use stream โ†’ read and / or write Catch exceptions if needed
  4. Close stream

Examples

See fileExamples package

Scanner Class Examples

Example 1

// old approach to scanning input BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); String name = br.readLine( ); // new approach using scanner Scanner in = new Scanner(System.in); String name = in.nextLine( ); int x = in.nextInt( );

Example 2

See ScannerExample.java Note use of printf

Annotations Annotation โ€“ Java construct that allow us to add validity constraints to Java Classes Validity constraint example A instance variable cannot assume a negative value A parameter can not be null A method in a class must override a method in its superclass Syntax at-sign (@) followed by annotation type and a parenthesized list of element-value pairs Example @DefaultAnnotationForParameters(NonNull.class) You can ignore annotations in code distribution for class projects

Reviewing Bit-Operations

Java Bitwise

operators

& and | or ^ exclusive or (xor) ~ complement

and x 11010 y 10110 x & y 10010 or x 11010 y 10110 x | y 11110 xor x 11010 y 10110 x ^ y 01100

BitSet Class

Implements a set of bits where the bits of the

set are indexed by nonnegative integers

Methods

BitSet() โ€“ New bit set BitSet(int nbits) โ€“ Bit set large enough to represent bits with indices from 0 through nbits โ€“ 1 and(BitSet set) โ€“ Performs logical and between the current object and the set parameter (current object is updated with the result) or(BitSet set) โ€“ Performs logical or between the current object and the setparameter (current object is updated with the result) cardinality() โ€“ Returns number of bits set to 1 flip(int bitIndex) โ€“ Sets the bit at the specified index get(int bitIndex) โ€“ Returns true if the bit at bitIndex is set; false otherwise length() โ€“ Index of the highest set bit + 1. It returns zero if the BitSet contains no bits set. size() โ€“ Number of bits space used by the BitSet to represent bit values toString() โ€“ For every bit set, the decimal representation of that index isincluded in the result.

Example (See Computers.java)