CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects classes which contain the methods which are the operations available to act upon an object of this type. Declarations create references which will be associated with the actual data thru its memory location (contents of the reference) when the new operator is executed Only operations supplied with the Object can be used to modify/access the data of the object Algorithms act upon the data of the problem/objects to carry out the task Class: encapsulates the data (private) and its operations (public) into one standalone unit. This unit can be separately compiled and integrated into any application. Java construct. Static class only one instance, All data and methods must be static Contains common algorithms with no data members (Math) Application class contains the main method Drives the application to carry out its tasks Coordinates the actions as carried out by the various objects cdtanner2.java, whardy23.java Instance class an instance created every time the new operator is executed Contains state (data members) and operations to access and manipulate the data Resusable Operations act upon an object of the class objectreceivingthemessage.classmethod() whardy23.java (Student) Abstract Data Type (ADT) Data Structure Collection of data and a set of operations that act upon the data Programming language construct that stores a collection of data array Conceptually minimal operations Create Add Remove Display
CS 111 Classes I 2 Return value Equal Copy Class Used for structuring data so it is more easily and efficiently stored, organized, and processed. Programming language construct that implements an ADT Encapsulates the data and operations which act upon the data into one module Allows for information hiding thru public and private All classes are at minimum of type OBJECT clone, equals, tostring Interface Specifies methods and constants for a set of classes Does not supply methods implementation Provides a contract and info needed to use the class Allows you to specify a desired common set of operations for a set of different types of objects Classes then implement the interface Programmer must supplied the methods stated when implementing the interface Can have many implementations each using different algorithm, etc. Must supply constructors, interfaces cannot be instantiated so they can not contain constructors Comparable, Clonable, Collection API ATM (verifypin, selectaccount, deposit, withdraw, showbalance) Package Groups related classes together to form a unit for compilation package pkgename; inserted as the first line of each file all files are placed in a directory of the same name import pkgename; By default all files in the same directory as the source file are in the default package therefore no import statement is necessary Consider a Date Data Members integers day, month, year Operations Create a date Specific d, m & y; specific d, specific d & m Set an existing date to a value
CS 111 Classes I 3 Advance to next day Display in two forms mm/dd/yyyy or January 1, 2011 equals tostring compareto clone accessors Consider a Playing Card Data members suit and integer face Suit spades, hearts, clubs, diamonds Special face values Ace, Jack, Queen, King Operations Create a card Random, specific Display equals samesuit sameface clone tostring accessors Consider an Arithmetic Problem Data members left operand, right operand, operator Operations Create a random problem displayproblem correctanswer Homework page 235 #5 & 6 Implementing a Class Access modifiers Public accessible by anything Private accessible only to other elements in the same class Data members declare private Class constants declared public Most class methods declare public Constructors Same name as class
CS 111 Classes I 4 No return type, not even void Executes automatically when a new object is created new Initializes the data members Default initialization int 0, double 0, boolean false, char, class null Must be at least one constructor if not compiler creates a null constructor (one without any parameters) if you create at least one (doesn t have to be the null constructor) the compiler will not create any accessors convention: getname() always supply mutators (setters) rarely supply only when domain specific equals overrides the equals in Object so the parameter passed must be of type object public boolean equals (Object a) instanceof operator (page 34) The parameter is of type Object (base class) we need to determine if the parameter is of the same data type for this classes equals public boolean equals(object a) return (a instanceof Date && a.day == day && a.month == month && a.year == year) a.day, a.month, a.year would all error terminate if a is not of type date ClassCastException takes advantage of short circuiting compareto returns 0 if ==, <0 if <, >0 if > public int compareto (Object a) Also uses Object as parameter type Type cast the parameter to the appropriate data type (Date) a clone creates a copy a = b sets references public Object clone()
CS 111 Classes I 5 returns the copy Polymorphism Generally, the ability to appear in many forms. In object oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. http://www.webopedia.com/term/p/polymorphism.html Sample programs Date.java, UseDate.java, Card.java, UseCard.java, Blackjack.java, Problem.java, Flash.java Homework: page 235 # 6 & 7 Exceptions (pages 40 48) Runtime errors raise exceptions Division by 0 ArithmeticException Array Bounds problem ArrayIndexOutOfBoundsException Incorrect argument type IllegalArgumentException Converting string >number NumberFormatException Null reference NullPointerException Next token when at end of a string NoSuchElementException Scanner next token is not correct data type InputMisMatchException Exceptions are defined in a class hierarchy which has Throwable as the base class Superclass Throwable Error Exception Assertion Error Others Runtime Exception Checked Exceptions Unchecked exceptions
CS 111 Classes I 6 All exceptions inherit from Throwable Methods in Throwable string getmessage() returns the detail message void printstacktrace () prints the stack trace string tostring() name of the exception Categories of Exceptions Checked not normally programmer errors Example I/O errors == IOException, EOFException, FileNotFoundException Need to be handled or use throws clause to say they are not handled Unchecked programmer errors that are considered unrecoverable Can handle them but are not required to (do not need throws clause) Catching and Handling exceptions Normal behavior when an exception is raised Terminate w/exception Message and stack trace are executed Instead catch the exception and try to recover from it Try Catch programming sequence try Statements which might cause the exception catch (exceptionname ex) Statements which handle the exception What the system does catch (exceptionname ex) system.err.println (ex.tostring()); ex.printstack(); system.exit(1); If exception is raised by the statements in the try block, control goes to the catch block(s) (there can be more than one catch block) It goes thru the catch blocks in order till it finds a match If no matching catch block is found the program error terminates
CS 111 Classes I 7 Executes the first catch block that matches the exception (or is a subclass of the exception) and continues on with the code It does not return to the try block unless there is a loop to force it back Finally block optional, executed after both the try and catch block Form of an exception handler try catch () catch () finally Programming Style Use exceptions to enable straightforward code Instead of if else if. Try catch. Etc More readable and less error prone Sample Programs: Exceptions.java Can also throw an exception on your own throw new exceptionname( message ); Sample Programs: Exceptions2.java Throws Clause Checked exceptions must either be handled or they are thrown to the previous level (method which called the method exhibiting the exception) compiler check Define that the method might throw and exception thru the throws clause throws exceptionname Any module which calls a module which might throw a checked exception must either write a try/catch block or use the throws clause Sample Programs: Exceptions3.java, Exceptions3a.java, Exceptions3b.java