1 / 40

CS221

Week 1 - Wednesday. CS221. Last time. What did we talk about last time? Course overview Policies Schedule. Questions?. OOP. What is an object?. Members Methods Why are they useful?. What is a class?. A template or prototype for an object. Object Oriented Programming. Encapsulation

crevan
Download Presentation

CS221

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Week 1 - Wednesday CS221

  2. Last time • What did we talk about last time? • Course overview • Policies • Schedule

  3. Questions?

  4. OOP

  5. What is an object? • Members • Methods • Why are they useful?

  6. What is a class? • A template or prototype for an object

  7. Object Oriented Programming • Encapsulation • Dynamic dispatch • Polymorphism • Inheritance • Self-reference

  8. Encapsulation • Information hiding • We want to bind operations and data tightly together • Consequently, we don't want you to touch our privates • Encapsulation in Java is provided by the private and protected keywords (and also by default, package level access) • Hardcore OOP people think that all data should be private and most methods should be public

  9. Encapsulation example public class A { privateint a; public intgetA() { return a; } public voidsetA(int value) { a = value; } }

  10. Inheritance • Allows code reuse • Is thought of as an is-a relationship • Java does not allow multiple inheritance, but some languages do • Deriving a subclass usually means creating a "refined" or "more specific" version of a superclass

  11. Inheritance example public class B extends A { //has member and methods from A } public class C extends A { //has A stuff and more private intc; public intgetC(){ return c; } void increment() { c++; } }

  12. Polymorphism • A confusing word whose underlying concept many programmers misunderstand • Polymorphism is when code is designed for a superclass but can be used with a subclass • If AudiRS5 is a subtype of Car, then you can use an AudiRS5 anywhere you could use a Car

  13. Polymorphism example //defined somewhere public void drive( Car car ) { … } public class AudiRS5 extends Car { … } Car car = new Car(); AudiRS5 audi = new AudiRS5(); drive( audi ); //okay drive( car ); //okay

  14. Dynamic dispatch • Polymorphism can be used to extend the functionality of an existing method using dynamic dispatch • In dynamic dispatch, the method that is actually called is not known until run time

  15. Dynamic dispatch example public class A { publicvoid print() { System.out.println("A"); } } public class B extends A { publicvoid print() { System.out.println("B"); } }

  16. Dynamic dispatch example A a = new A(); B b = new B(); // B extends A A c; a.print(); // A b.print(); // B c = a; c.print(); // A c = b; c.print(); // B

  17. Self-reference • Objects are able to refer to themselves • This can be used to explicitly reference variables in the class • Or, it can be used to provide the object itself as an argument to other methods

  18. Self reference example public class Stuff { privateint things; public voidsetThings(intthings) { this.things = things; } }

  19. Self reference example public classSelfAdder { publicvoidaddToList(List list) { list.add(this); } }

  20. Constructor syntax • Java provides syntax that allows you to call another constructor from the current class or specify which superclass constructor you want to call • The first line of a constructor is a call to the superclass constructor • If neither a this() or a super() constructor are the first line, an implicit default super() constructor is called

  21. Constructor example public class A { private double half; public A(int value) { half = value / 2.0; } } public class B extends A { publicB(int input) { super(input); // calls super constructor } publicB() { this(5); // calls other constructor } }

  22. Interfaces

  23. Interface basics • An interface is a set of methods which a class must have • Implementingan interface means making a promise to define each of the listed methods • It can do what it wants inside the body of each method, but it must have them to compile • Unlike superclasses, a class can implement as many interfaces as it wants

  24. Interface definition • An interface looks a lot like a class, but all its methods are empty • Interfaces have no members except for (static final) constants public interface Guitarist { voidstrumChord(Chord chord); voidplayMelody(Melody notes); }

  25. Interface use public class RockGuitaristextendsRockMusicianimplements Guitarist { public voidstrumChord( Chord chord ) { System.out.print( "Totally wails on that "+ chord.getName() + " chord!"); } public void playMelody( Melody notes ) { System.out.print( "Burns through the notes " + notes.toString() + " like Jimmy Page!"); } }

  26. Usefulness • A class has an is-a relationship with interfaces it implements, just like a superclass it extends • Code that specifies a particular interface can use any class that implements it public static void perform(Guitarist guitarist, Chord chord, Melody notes) { System.out.println("Give it up " +"for the next guitarist!"); guitarist.strumChord( chord ); guitarist.playMelody( notes ); }

  27. Exceptions

  28. Exceptions • Java handles errors with exceptions • Code that goes wrong throws an exception • The exception propagates back up through the call stack until it is caught • If the exception is never caught, it crashes the thread it's running on, often crashing the program

  29. Kinds of exceptions • There are two kinds of exceptions: • Checked • Unchecked • Checked exceptions can only be thrown if the throwing code is: • Surrounded by a try block with a catch block matching the kind of exception, or • Inside a method that is marked with the keyword throws as throwing the exception in question • Unchecked exceptions can be thrown at any time (and usually indicate unrecoverable runtime errors)

  30. Examples of exceptions • Checked exceptions • FileNotFoundException • IOException • InterruptedException • Any exception you write that extends Exception • Unchecked exceptions • ArrayIndexOutOfBoundsException • NullPointerException • ArithmeticException • Any exception you write that extends Error or RuntimeException

  31. Exceptions in code Scanner in = null; try { in = new Scanner( file ); while( in.hasNextInt() ) process( in.nextInt() ); } catch( FileNotFoundException e ) { System.out.println ("File " + file.getName() + " not found !"); } finally { if( in != null ) in.close(); }

  32. Threads

  33. Threads • In Java, concurrency and parallelism are achieved primarily through threads • A thread is a path of code execution that runs independently of others • But threads can share memory with each other • Some other languages use message passing semantics and no direct memory sharing

  34. Creating threads in Java • To create a customized thread in Java, there are two routes: • Create a class which is a subclass of Thread • Create a class which implements the Runnable interface • If you subclass Thread, you can't subclass some other object • If you implement Runnable, there's an extra bit of syntax to create a new thread

  35. Sample thread to sum things public class Summer extends Thread { private double[] array; private intstart; private intend; private double result = 0.0; public Summer(double[] array, intstart, intend) { this.array = array; this.start = start; this.end = end; } public void run() { for( inti = start; i < end; i++ ) result += array[i]; } public double getResult() { return result; } }

  36. Using Summer public double findSum( double[] array, intthreads ) throwsInterruptedException { Summer[] summers = new Summer[threads]; double result = 0.0; intstep = array.length / threads; if( array.length % threads > 0 ) step++; for( inti = 0; i < threads; i++ ) { summers[i] = new Summer(array, i*step, Math.min((i+1)*step, array.length)); summers[i].start(); } for( inti = 0; i < threads; i++ ) { summers[i].join(); result += summers[i].getResult(); } return result; }

  37. Tips for concurrency • Keep it simple • Do not share data via static variables • Be careful with load balancing • If the work is not evenly divisible by n (the number of threads), give the first n – 1 threads one extra piece of work • Why? • Be aware that threading out a program will not necessarily make it faster

  38. Upcoming

  39. Next time… • Inner classes • Generics • Java Collection Framework

  40. Reminders • Continue to read Chapter 1 • Keeping brushing up on Java if you are rusty • Project 1 will be assigned Friday • Send me an e-mail with your team members in it by Friday, August 29

More Related