CS 2 - PowerPoint PPT Presentation

1 / 59
About This Presentation
Title:

CS 2

Description:

Java Basics. Primitive Data Types. boolean, char, byte, short, int, long, float, double ... Java Basics. Main Method. Invoked automatically when a class is sent ... – PowerPoint PPT presentation

Number of Views:36
Avg rating:3.0/5.0
Slides: 60
Provided by: ccGa
Category:
Tags: basics

less

Transcript and Presenter's Notes

Title: CS 2


1
CS 2
  • Introduction to
  • Object Oriented Programming
  • Final Review
  • Spring 2004

2
Preliminaries
  • Pop Quiz 4 results

3
Preliminaries
  • Please fill out the
  • GT Official course survey
  • www.coursesurvey.gatech.edu/student_login.cfm
  • CS1322 survey (this is the extra credit one) on
    WebCT

4
Preliminaries
  • Study early and often, dont wait till nite
    before there is a lot of material
  • The time to earn your grade is now, not after the
    course is over
  • 20 - HWs
  • 5 - quizzes
  • 45 - exams
  • 30 - final
  • 1 - survey

5
Preliminaries
  • I will be away Sat through Thursday

6
Java Basics
  • Primitive Data Types
  • boolean, char, byte, short, int, long, float,
    double
  • Implementation precisely defined i.e. not machine
    dependent
  • Declarations
  • int x
  • int x 42
  • Casting Potential loss of information requires
    cast

7
Java Basics
  • Main Method
  • Invoked automatically when a class is sent to JVM
    (java)
  • Could be invoked like any other method (not
    typical)
  • Can pass in arguments as String array

8
Java Basics
  • Control Structures
  • Loops
  • while
  • do...while
  • for
  • Conditionals
  • switch
  • if/else

9
Java Basics
  • Modularity
  • methods
  • procedures no return
  • functions return a value
  • parameters
  • pass by value (in parameters only)
  • type and order designate signature
  • returns
  • return causes immediate return to calling program
  • return with value for function
  • return with no value for procedure (optional)

10
Java Basics
  • Visibility Specifiers
  • public (all)
  • protected (package inherit)
  • private (class only)
  • (nothing) -- package
  • Method
  • Overloading
  • Overriding
  • Instance
  • Class (static)

11
Java Basics
  • Recursion (Just knowing 1321 stuff)
  • Comments
  • Multiline / /
  • Single line //
  • Javadoc
  • /
  • Plus Doc-Comment Tags
  • _at_return
  • _at_param
  • _at_version
  • _at_throws
  • etc.

12
OO
  • Objects
  • Strings
  • 1D arrays
  • int gradeArray new int10
  • references
  • null
  • ltClassNamegt ltidentifiergt
  • creates a reference to an object which is either
    an instance of ltClassNamegt or a instance of a
    child class of ltClassNamegt
  • versus .equals( )

13
Objects and References
When working with References to Objects, Java has
two logical operations
2.
1.

Creates a new area in memory so each named
reference points to its own object
Two references to a single area of memory
14
Example
Assignment with References to Objects
15
Objects and References
Equality with References to Objects
  • Two different logical tests available
  • 1. The operator (equality)
  • It evaluates whether two references point
    to the same object.
  • 2. The method equals( )
  • It evaluates whether the internal state (i.e.,
    contents) of one object is identical to the
    internal state of another object.
  • It is a special method built-in to the class
    Object, and is available to all classes you
    create. In practice you will want to code a
    version of equals() in your classes, so that you
    can compare objects.
  • You have to code this method in all data
    classes you create, or else you are stuck with
    the most stringent test, i.e.,

For primitives
For objects
16
OO
  • Variables
  • Instance vs. class variables
  • When to use which
  • Encapsulation
  • Information hiding

17
Instance vs. Class Variables When to Use
Quiz Alert!
Use instance variables whenever each object
should have its own variable. E.g., attributes
of the particular object. Use a class
variable whenever the class itself should
maintain a single copy of datum pertaining to all
instances of the class. E.g., population
counts summary data assigning
lot numbers shared resources.
18
Quiz Yourself
Consider why the following code will not compile
  • public class Test
  • public void sayHello()
  • System.out.println (Hello)
  • public static void main (String arg)
  • sayHello() // WRONG!

19
OO
  • Classes
  • Encapsulation
  • Data attributes
  • Behaviors
  • Constructors
  • Chaining
  • Methods
  • Accessors
  • Modifiers
  • Overloading Multiple methods with same name (in
    same class) with different parameter lists.
  • Overriding Class defining a method with same
    name, return type and parameters as superclass
    method

20
Classes and Objects
Class describes the form of an object, a
template or blueprint or mold specifies data
representation, behavior, and inheritance (via
variables, methods and parents)
Object an instance of a class has unique copy
of every non-static variable (i.e., the instance
variables but not the class variables).
Difference between a class and an object of
that class is analogous to the difference
between a type and a variable of that type.
Naming Conventions Classes Identifiers begin
with cap letters for each word in
the Identifier, e.g., class NeuralNetwork Objects
Identifiers begins with lower case letter,
then caps for other words in identifier,
e.g., thisObjectIdentifier
21
Vocabulary
Encapsulation Placing all entity attributes
and behavior in a single class. In other words,
we encapsulate by placing variables and mutators
to change these variables in a class. This is
one of the KEY aspects of OO programming.
It will be asked on tests over and over again.
22
OO
  • Classes (continued)
  • Shadowing
  • Field name in subclass shadows field with same
    name in superclass.
  • Accessed via super.ltfieldnamegt
  • this
  • this.ltfieldnamegt
  • this.ltmethodnamegt(...)
  • this(...)
  • super
  • super.ltfieldnamegt
  • super.ltmethodnamegt(...)
  • super(...)

23
OO
  • Classes (continued)
  • scope
  • public class A
  • int b
  • void method()
  • int b
  • ...
  • System.out.println(b)
  • System.out.println(this.b)
  • System.out.println(super.b)

24
An Abstract Class
  • A class like Animal is intended as a collector of
    common characteristics
  • We want to refer to methods like move()
    polymorphically
  • However, we have no idea how a generic animal
    really moves.
  • We could use some meaningless surrogate code
  • public void move ( )
  • System.out.println(I am an animal and am
    moving.)
  • // of move
  • We could just give up and use an empty method
    like
  • abstract public void move ( )
  • This, of course, does nothing, and we depend on
    child classes to implement these methods
  • We use the keyword abstract to indicate that at
    least one method must be implemented in all child
    classes
  • public abstract class Animal

25
OO
  • N-D arrays
  • Widget w new Widget4
  • w0 new Widget3
  • w1 new Widget5
  • w2 new Widget7
  • w3 new Widget4
  • Inheritance
  • extends (isa)
  • Interfaces
  • for constants
  • implements
  • Allows behavior like multiple inheritance
    without some of the potentially messy problems of
    multiple inheritance

26
Interfaces Defined
  • -Sometimes considered the ultimate abstract class
    - contains nothing but constants and abstract
    method prototypes
  • -A class is said to implement an interface if it
    provides suitable real methods for all of the
    abstract (virtual) methods of the interface
  • -The class implementing that interface then
    behaves as if it were inheriting from a parent
    class, with one huge advantage
  • Since you implement all of the abstract methods
    yourself, there is no other hidden, inherited
    stuff to collide with
  • -You can therefore implement as many interfaces
    as you wish with no fear of the problems of
    multiple inheritance

27
OO
  • Dynamic binding
  • At compile time a method call is checked to make
    sure the reference type has that method
  • At run time the method actually invoked is
    determined by looking first in the actual object
    being referenced (not the class of the
    reference). If not found the search is made up
    the inheritence tree until a matching method is
    found.
  • Animal a new Poodle()
  • a.speak() / Animal must have a speak method to
  • compile but at runtime the Poodle
  • speak method will be invoked and if
  • not present then Dog will be
    checked
  • followed by Animal. /
  • // No speak in Poodle?
  • (Poodle)a.speak()

28
Dynamic Binding
Object oTemp oTemp animalArray1 Animal
aTemp (Animal) oTemp aTemp.move()
aTemp
Understand this term. Understand what is does.
You WILL have many, many, many, quiz and final
exam questions on this. It is a CORE feature
of any Object Oriented language.
Here, the principle of dynamic binding will
ensure that at run time, the most specific
behavior will be invoked. Here, the Fish move()
method is more specific than its parent method.
So, the Fishs move() method gets called with the
aTemp.move() line.
29
Sanity Check
Object oTemp oTemp animalArray1 Animal
aTemp (Animal) oTemp System.out.println
(oTemp.toString())
oTemp
Does casting somehow overpower dynamic binding?
What Happens Here?
NEVER.
What about System.out.println (
((Object)oTemp).toString() )
30
Sanity Check
Object oTemp oTemp animalArray1 Animal
aTemp (Animal) oTemp System.out.println
(oTemp.toString())
oTemp
No matter how you cast things, dynamic binding
takes hold. Its like the law of gravity.
What Happens Here?
What about System.out.println (
((Object)oTemp).toString() )
31
Sanity Check
Object oTemp oTemp animalArray1 Animal
aTemp (Animal) oTemp System.out.println
(oTemp.toString())
oTemp
No matter how you cast things, dynamic binding
takes hold. Its like the law of gravity.
What if Fish had its own toString()?
Dynamic binding will always resolve, at run time,
to the most specific version of the method.
ALWAYS.
32
Always?
Object oTemp oTemp animalArray1 oTemp.move
() // WRONG!
oTemp
No such method move() in Object
Does dynamic binding also work miracles? That
is, does it let you find methods in extending
classes, if the present class does not have such
a method?
NO. This would cause a compile time error. Java
is strongly typed, meaning that each time you
invoke a method, the method MUST be present in
the class--even if dynamic binding would later
find a more specific version. So no, dynamic
binding does not trump type safety in Java.
33
OO
  • Polymorphism
  • Animal a
  • a.speak( ) / Can be executed no matter what
    particular type of animal a is referencing as
    long as there is a speak method in the particular
    objects hierarchy (and animal). /
  • Generic data structures
  • Typical Java solution Make structures that hold
    Objects
  • Works since every class in Java is a descendant
    of class Object
  • Requires casting of objects removed from
    container back to their actual type

34
Polymorphism
  • Polymorphism means taking many forms ... A
    reference of a given class can adapt or take
    the form of any of its subclasses.
  • Polymorphism means that the correct move( )
    method will always be called.
  • Polymorphism is legal in the State of Georgia
  • A subclass can be substituted for its
    superclass, e.g., a bird for an animal. A
    bird is a animal. Yes.
  • The reverse is not true cant substitute
    superclass for a subclass, e.g.,
  • CANNOT substitute an animal for a bird.
  • An animal is a bird? No.
  • A single interface for multiple behaviors
    Only one interface for the method call.
  • Multiple behaviors based on the subclass.

35
Why?
Object
Animal
36
Object
Dog
Animal
Object
Dog d new Dog()
Dog d new Animal()
Dog d new Object()
Object
REF
REF
REF
Dog
Animal a new Dog()
Animal a new Animal()
Animal a new Object()
Object
REF
REF
REF
Animal
Reference
Object o new Dog()
Object o new Animal()
Object o new Object()
Object
REF
REF
REF
Object
Could this be some form of Matrix?
37
abstract class Furniture public int
numlegs abstract void meth1() class
Recliner extends Furniture void meth1()
System.out.println(Im a recliner)
class LaZBoy extends Recliner void
meth1() System.out.println(Im a
laZBoy)
1. Will this compile? 2. Will it run? 3. What
is output?
Recliner recl recl new LaZBoy() recl.meth1()

38
abstract class Furniture public int
numlegs abstract void meth1() class
Chair extends Furniture public String
fabric class Recliner extends Chair
void meth1() System.out.println(Im a
recliner) class LaZBoy extends
Recliner void meth1()
System.out.println(Im a laZBoy)
1. Will this compile? 2. Will it run? 3. What
is output?
Furniture furn furn new LaZBoy() furn.meth1()
39
abstract class Furniture public int
numlegs abstract void meth1() abstract
class Chair extends Furniture public String
fabric abstract void meth1() class
Recliner extends Chair void meth1()
System.out.println(Im a recliner)
class LaZBoy extends Recliner void
meth1() System.out.println(Im a
lazboy)
1. Will this compile? 2. Will it run? 3. What
is output?
Furniture furn furn new Recliner() furn.meth1(
)
40
abstract class Furniture public int
numlegs abstract void meth1() abstract
class Chair extends Furniture public String
fabric abstract void meth1() class
Recliner extends Chair void meth1()
System.out.println(Im a recliner)
class LaZBoy extends Recliner void
meth1() System.out.println(Im a
lazboy)
1. Will this compile? 2. Will it run? 3. What
is output?
Chair cha cha new LaZBoy() cha.meth1()
41
OO
  • OO Design
  • Design from high level down to low level
  • Create diagrams/sets of cards/files which define
    Classes
  • For each class designate
  • Data to be stored by the class
  • Methods the class will be able to perform
  • Communication with other classes
  • Walk through operation of the system to verify
    that the structure works (modifying as necessary)
  • Code individual classes and debug using test main
    as far as possible

42
Data Structures
  • Linked Lists (Ordered, Unordered, Indexed)
  • Trees
  • Stacks
  • Queues
  • Bags
  • Hashtables
  • Graphs
  • Basic Arrays

43
What data structure?
  • I need to keep a group of objects so that I can
    rapidly get at the last object I entered.
  • I need to model trucks being serviced at a
    warehouse where the first truck to arrive is the
    first handled.
  • I need to keep some items around, but do not need
    any particular order.
  • I need to rapidly access a particular position
    (like the 5th element).

44
What data structure?
  • I need to rapidly get a particular item, but I
    dont care what order they are in.
  • I need to keep things in sorted order.
  • I need to rapidly find the maximum and minimum
    values in a collection.
  • I need to keep a collection where I can rapidly
    insert or delete any particular element.

45
What data structure?
  • I need to model the internet, and the time it
    takes to send packets between routers.
  • I need to compute shortest paths between cities.
  • I need to rapidly lookup information about
    something that has a unique key (like SSN).

46
Summary of Hash Tables
  • Purpose Fast searching of lists by reducing
    address space to approx. population size.
  • Hash function the reduction function
  • Collision hash(a) hash(b), but a!b
  • Collision resolution strategies
  • Multiple element buckets still risk collisions
  • Open addressing quickly deteriorates to unordered
    list (linear probing, quadratic probing,
    secondary hash)
  • Chaining is most general solution

47
Algorithms
  • BFS/DFS with Graphs
  • Tree Traversals
  • Inorder
  • Preorder
  • Postorder
  • LevelOrder

48
Advanced Java
  • Exceptions
  • File IO
  • Applets
  • Swing

49
What happens when an exception is thrown
  • An exception object is created (on the heap)
  • The current context is halted/aborted
  • Execution starts in some error handling code
  • Can be in current method
  • Can be external to current method
  • The error handling code has access to the
    exception object which can be used to
  • Access a String message contained in the
    exception
  • Determine what type of exception was thrown
  • Print a stack trace
  • Other cool stuff (like rethrow the exception,
    increment a counter, etc.)

50
File IO
  • Based on Streams
  • Character (aka text)
  • Readers (Input) i.e. FileReader
  • Writers (Output)i.e. FileWriter
  • Byte (aka binary)
  • InputStream (Input) i.e. FileInputStream
  • OutputStream (Output) i.e. FileOutputStream
  • Processing Stream
  • Wraps Character or Byte streams to provide more
    functionality or filter stream
  • Most common Buffered streams to allow line at a
    time processing i.e. BufferedInputStream,
    BufferedReader

51
GUIs, AWT Swing
  • GUIs
  • paintComponent in JPanel
  • repaint
  • Components
  • Containers
  • Events
  • Listeners
  • Graphics

52
Containers
STEP 1
Containers are special components that may
contain other components.
Note Containment is not the same as inheritance
extension. A Frame may contain buttons, but
buttons are not subclasses of Frame.
53
Components
STEP 2
Most interactions in a Java GUI are with
Components. Another generic term for Component
is other GUIs (e.g. X Windows) is
"widget". Different types of components for
different types of interaction (e.g. buttons,
etc.) User interactions with components create
events (thus, event- driven programming) As a
rule, a Component cannot have other components
inside Exceptions to rule pop up menus may have
menu items added to them. And Containers are
themselves components due to inheritance.
54
Layout Managers -- AWT Based
  • Java provides several layout managers.
  • We will concentrate here on several of them
  • BorderLayout
  • GridLayout
  • FlowLayout
  • BoxLayout
  • To tell a container which layout manager to use,
    invoke the method
  • setLayout( )
  • and specify a type of layout.
  • For example
  • To specify a BorderLayout
  • setLayout (new BorderLayout())

55
Events
Java uses a delegation event model found in
many other toolkits. Under the delegation model,
components fire events, which can be caught and
acted on by listeners. A listener is linked to a
component through a registration process. The
delegation event model is contrasted to an event
filtration model where all events are delivered
to target components regardless of whether they
asked for them.
56
Graphs Terminology
A Graph is a set of vertices (nodes) and a set of
unordered edges (linked between these
nodes). The order of a graph is the number of
vertices and the size is the edge count. A path
is a set of edges connecting two nodes. A
digraph or directed graph has edges (arcs) that
flow in only one direction. In an undirected
graph, edges flow in either direction.
57
Final Exam
  • Bring BuzzCard
  • Travel light
  • Wed 8am, 2h 50m (15-20 questions bonus)
  • Test Taking Strategies
  • Relax!
  • Timing/Pacing
  • Show all work (partial credit)
  • Answer what you do know
  • Points for headers/signatures
  • Points for return statements

58
Feedback
  • What did you think about the course?
  • What you expected/different

59
Thanks for being here!
  • Good luck on your exams!!!
Write a Comment
User Comments (0)
About PowerShow.com