Title: CS2
1CS2
- Introduction to
- Object Oriented Programming
- Course Review
2- CS 1322 Official Final Exam Schedule
- Section B (1200-145 lecture)
- Lecturer Bill Leahy
- Final Exam
- Date Wednesday, August 1, 2001
- Time 250-540
- Location Physics L3 (Normal class meeting
location) - Bring pencils, eraser. No books, notes,
calculators, etc. - No one will be admitted after 305 p.m.
3http//www.coursesurvey.gatech.edu
Please complete
Use your Banner ID and PIN
4Java 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 - Main Method
- Invoked automatically when a class is sent to JVM
(java) - Could be invoked like any other method (not
typical)
5Java Basics
- Control Structures
- Loops
- while
- do...while
- for
- Conditionals
- switch
- if/else
- System.out.println
- Debugging (bDEBUG)
- Tracing
6Java 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)
7Java Basics
- Visibility Specifiers
- public
- protected -- ???
- private
- Method
- Overloading
- Overriding
- Instance
- Class
8Java Basics
- Recursion
- Comments
- Multiline / /
- Single line //
- Javadoc
- //
- Plus Doc-Comment Tags
- _at_return
- _at_param
- _at_version
- _at_throws
- etc.
9OO
- 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( )
10Objects 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
11Example
Assignment with References to Objects
12Objects 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
13OO
- Variables
- Instance vs. class variables
- When to use
14Instance 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.
15Quiz 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!
-
16OO
- 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
17Classes 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
18Vocabulary
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.
19OO
- 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(...)
20OO
- 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)
-
21An 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
22OO
- 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
23Interfaces 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
24OO
- 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()
25Dynamic 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.
26Sanity 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() )
27Sanity 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() )
28Sanity 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.
29Always?
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.
30OO
- 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
31Polymorphism
- 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.
32Why?
Object
Animal
33Object
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?
34abstract 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()
35abstract 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()
36abstract 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(
)
37abstract 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()
38OO
- 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
39Data Structures
- Linked Lists
- Trees
- Stacks
- Queues
- Heaps
- Hashtables
40Summary of Basic Heap Properties
- Structure Property
- organize the data as a complete binary tree
- enables operation in logN time
- Order Property
- In a heap, for every node X with parent P, the
key value in P is smaller than or equal to X - Forces the minimum value to be the tree root
- Tree Operations
- may disturb one or both properties
- not considered complete until the properties are
restored
41Summary 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 - Chaining is most general solution
42Algorithms
- BFS/DFS with Graphs
- Tree Traversals
43Advanced Java
44What 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.)
45Vectors
- Vector is a class that provides a dynamic
collection, similar to a Linked List, Queue, etc. - Must be instantiated via new to get an
instance of Vector. - Vector elements are accessed via various utility
methods
size( ) returns current number of
elements. elementAt(int index) returns reference
to element at
specified index. insertElementAt( Object obj,
int index ) ala insertion into linked list
(but slower) cannot do at
end. addElement (Object obj) adds to end.
Commonly used methods
46GUIs, AWT Swing
- GUIs
- paintComponent
- repaint
- Components
- Containers
- Events
- Listeners
- Graphics
47Containers
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.
48Components
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.
49Layout 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())
50Events
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.
51Graphs 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.
52Intro to C
- Introduction to C
- Differences between Java and C
- Pointers and Structures
- How are parameters passed in C?
- How do you pass a structure
- How do you pass a pointer to a structure
- Input/Output
- printf
- scanf
53Structures
- Structures
- can be copied or assigned
- can have their address taken using
- can be passed to and returned from functions
- struct point doublePoint(struct point in)
- struct point temp
- temp.x 2 in.x
- temp.y 2 in.y
- return temp
-
- may be initialized
- struct point maxpt 320, 200
- can be used in arrays (arrays of structs)
54Pop Quiz
- include ltstdio.hgt
- void print_num (int x)
-
- printf("Number d\n", x)
-
- int main (void)
-
- int a 3
- int b
- b a
- print_num(??)
- return 0
-
Which one goes here to print 3? b b b
55Pop Answer
- include ltstdio.hgt
- void print_num (int x)
-
- printf("Number d\n", x)
-
- int main (void)
-
- int a 3
- int b
- b a
- print_num(b)
- return 0
-
56Pop Quiz
- include ltstdio.hgt
- void print_num (int x)
-
- printf("Number d\n", x)
-
- int main (void)
-
- int a 3
- int b
- b a
- print_num(b)
- return 0
-
b Pointer to an int b What b is pointing
at b Address where b is stored
57Final Exam
- Bring BuzzCard
- Travel light
- 2h 50m
- Test Taking Strategies
- Relax!
- Timing/Pacing
- Show all work (partial credit)
58Feedback
- What did you dislike about the course?
59Feedback
60Feedback
- What would you do differently?
61Feedback
62Thanks for being here!
- Good luck on your exams!!!
63(No Transcript)