Outline • Feedback • Background CS1007: Object Oriented Design – Arrays – Scopes and Programming in Java – Static – Method Overloading – Basic classes – Constructors Lecture #3 – Useful tools T 1/24 – Exception handling – File handles Shlomo Hershkop shlomo@cs.columbia.edu • Reading: Chapter 1, and any relevant background reading Feedback Announcements • More clarification on THIS • Homework 1 out by next class – Start early • Practical java examples – If you are having problems…you probably have not seen HW0 – Limited now, since we need to cover background material, but will be doing – Will be doing snippets in class complex examples during class • Practice homework online – Basic idea will be to create a multi class – Will make solutions available project and have fun. 1
Office hours Announcements II • My • Slides will be on website within 24hrs after class – T/Th 1-2pm, 4-4:30pm – By appointment • Privilege • Ohan • Don’t want to see drop in attendance, – T 11-1 or 12-2 being here allows a discussion to take place – Fr 12-2 This Class objects public class student{ • Represents an idea/concept/construct String name; Date recordStart; • Field variables int idNumber; • Constructors – Default public void setName(String name){ • Public methods this.name = name; – Accessors } – Mutators • Private methods } 2
Constructor Default Constructor • A constructor is a method that gets called when an object is created • If we don’t define a constructor the default using new . constructor with not parameters will be created. • We can use the constructor to initialize the fields of the object. • A constructor can have as many parameters as necessary, but can not have a return type. • So we can say: Account m = new Account(); public class Account { private int id; • Like other methods, the constructor can also be overloaded (more on this later) public Account(int id){ this.id = id; • Can call one constuctor from another } – this(argument list); } – Must be the first statement in the method Methods Method Overloading • Methods are defined by their signatures • We can define two methods with the same – permissions name, as long as they have different – Return values signatures – Argument values – Different input parameters – modifiers or/and – Different return values public void foo() Java will know which one to use public int foo() 3
Exceptions Exception Handling • Example: NullPointerException • Object that represents an unusual event or an error String name = null; int n = name.length(); // ERROR • Attempt to divide by zero • Cannot apply a method to null reference • Virtual machine throws exception • Array out of bounds • Unless there is a handler, program exits with stack trace • Null reference Exception in thread "main" java.lang.NullPointerException at Student.setname(Student.java:15) at StudentTest.main(StudentTest.java:20) Checked and Unchecked Declaring Checked Exceptions Exceptions • Example: Opening a file may throw FileNotFoundException: • Compiler tracks only checked exceptions • NullPointerException is not checked public void read(String filename) throws FileNotFoundException • IOException is checked { FileReader reader = new FileReader(filename); • Generally, checked exceptions are thrown for . . . reasons beyond the programmer's control } • Two approaches for dealing with checked • Can declare multiple exceptions exceptions public void read(String filename) – Declare the exception in the method header throws IOException, ClassNotFoundException (preferred) public static void main(String[] args) throws IOException, ClassNotFoundException – Catch the exception 4
The finally Clause Catching Exceptions try • Will ALWAYS execute code block – Even if return statement in try block { • Cleanup needs to occur during normal and exceptional processing code that might throw an IOException • Example: Close a file } catch (IOException exception) FileReader reader = null; { try take corrective action } { reader = new FileReader(name); ... • Corrective action can be: – Notify user of error and offer to read another file } catch..... – Log error in error report file finally – In student programs: print stack trace and exit { if (reader != null) reader.close(); exception.printStackTrace(); } System.exit(1); Java packages Packages • Collection of similar classes • Unique package names: start with reverse domain name • Package names are dot-separated • Corresponds to directory structure identifier sequences – Must match directory structure • package statement to top of file java.util • Class without package name is in "default package“ javax.swing • Full name of class = package name + class com.sun.misc name edu.columbia.cs.robotics java.util.String 5
Importing Packages Arrays • Tedious to use full class names • Ordered list of objects can be organized in • import allows you to use short class name an array • Array properties import java.util.Scanner; – Capacity . . . – Size Scanner a; // i.e. java.util.Scanner – Can be treated as a single object (to an extent) • Can import all classes from a package import java.util.*; Arrays Arrays • Array access with [] operator: • Arrays can store objects of any type, but their length is fixed int n = numbers[i]; • length member yields number of elements int[] numbers = new int[10]; • Array variable is a reference for (int i = 0; i < numbers.length; i++) ref • Or use "for each" loop for (int n : numbers) 6
Command Line Arguments Arrays public static void main(String[] args) • Can have array of length 0; not the same as null: • args , is an array of string. • The elements of args are the command line • numbers = new int[0]; arguments using in running this class. Java testProgram –t –Moo=boo out.txt • Multidimensional array 0: ‘-t’ 1: ‘-Moo=boo’ 2: ‘out.txt’ Two dimensional arrays • You can create an array of any public class TicTacToe{ public static final int EMPTY = 0; object, including arrays public static final int x = 1; • int[][] table = new int[10][20]; public static final int y = 2; • int t = table[i][j]; private int[][] board = { {EMPTY, EMPTY, EMPTY}, • An array of an array is a two {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY} dimensional array } 7
Two dimensions Multiple dimensions • You can also initialize the inner array as a • No reason cant create 4,5,6 dimension separate call. arrays • Doesn’t have to be congruous memory locations • Gets hard to manage • Think about another way of representing int [][]example = new int[5][]; the data for (int i=0;i<5;i++){ • Often creating an object is a better example[i] = new int[i+1]; approach } Arrays further Scope • Need to explicitly copy contents of arrays • Scope refers to where java programming objects variables/methods/classes can be accessed. • ArrayList • Vector • Local • Full object versions of arrays • Global • Package • Capacity can grow over time • Universal 8
Variables Instantiated vs static • Variables declared within a method are local to • When you define a method in a class, that method every instance of the class has its own – Local scope copy. • Variables declared within a class, are called field variables – Class wide scope • Including subclasses • static methods allows one copy to be – Package wide scope accessed by all instances – So……what parts of the class should it be • Local variable can have the same name as field variables able to access? – Use this to disambiguate Static Fields Static Methods • Shared among all instances of a class • Don't operate on objects • Example: Math.sqrt • Example: shared random number generator • Example: factory method public class Greeter public static Greeter getRandomInstance() { { . . . if (generator.nextBoolean()) // note: generator is static field private static Random generator; return new Greeter("Mars"); } else return new Greeter("Venus"); } • Example: shared constants • Invoke through class: public class Math { Greeter g = Greeter.getRandomInstance(); . . . public static final double PI = 3.14159265358979323846; • Static fields and methods should be rare in OO programs } 9
Pass around main • Can in theory use static variables to pass • The main method is declared public, static around values between class instances and void. • Because it is static we often need to create an instance of the class inside its own main. • When is this good? • Why? • Why? • Why Not? main Default values • Every class can have a main method. If • Should be aware if you forget to set values you five classes, with each one having a • Compiler/IDE will let you know if you forgot main, you need to tell java which one to to set values (warning) run… • How is this done? • Can also use individual mains as testing areas, will be ignored when not run 10
Recommend
More recommend