Title: Introduction to Object Oriented Programming in Java
1Introduction to Object Oriented Programming in
Java
- Sandy GrahamUniversity of Waterlooslgraham_at_uwate
rloo.ca - Imperial Oil Summer Institute
- for Computer Studies EducatorsAugust 14, 2007
2What is Object-Oriented Programming (OOP)?
- Design, programming, and languages
- An alternative to procedural programming
- anything done using OOP can also be done using a
procedural paradigm - Considering a problem from the perspective of
objects and how they interact
3Skills for OOP
- Must have a solid understanding of subprograms
and parameters - stepwise refinement
- Should understand references/pointers
- Coding still involves basic concepts
- selection structures, repetition structures,
variables, arrays
4OOP vs. Procedural
- Procedural Paradigm
- Program defines data and then calls subprogram to
act on the data - Object Paradigm
- Program creates objects that encapsulate the data
and procedures that operate on the data
5Java Background
- The SDK (system developers kit) is used to
compile and run Java applications and applets - A Java program is composed of a number of classes
you write, that work together - Each class is in a separate file
- At least one file must contain the main method
starting point of the program - Most programmers use an IDE (Integrated
Development Environment), such as Dr. Java - Includes an editor, a compiler, a JVM, and access
to Java libraries - The JVM (Java Virtual Machine) interprets the
byte code and converts it to machine code - The JVM is native to the machine
6Why use Java?
- Java was created by Sun Microsystems and is free
(http//java.sun.com/) - It is platform independent
- i.e. a program can be written on a computer with
one operating system, but run on a computer with
a different operating system - Became very popular with the increase in use of
the internet - Webbrowsers have built in JVMs that could run
Java applets - There are many useful classes that have been
written and shared - Some classes are automatically available
java.lang library - Some classes may be imported other Sun Java
libraries - Custom classes may be accessed by adding a
classpath - An industry standard programming language
- Students will be prepared for many first year
programs in Computer Science and Engineering
7Basic Concepts
- Objects
- Hidden data that is accessed and manipulated
through a well-defined interface of method calls - Classes
- A template or blueprint for creating objects,
each with their own data - Inheritance
- A new class created by modification of an
existing class
8Objects
- Part of a program which
- models some real or conceptual object
- has behavioural responsibilities (behaviours)
- has informational responsibilities (attributes)
- Behaviours (methods)
- things an object can do
- like procedures and functions in other languages
- Attributes (fields)
- information an object knows (has-a)
- like data and variables in other languages
(records)
9Classes
- A class is a template. No data is allocated until
an object is created from the class. However
attributes and behaviours are generically
defined. - A class is a valid data type for a variable after
it has been defined - The creation (construction) of an object is
called instantiation. The created object is often
called an instance (or an instance of class X) - One class, 0 to many objects
10Analogies for Classes Objects
- Class
- blueprint
- pattern
- cookie cutter
- factory
Object building garment cookie widget
Platos allegory of the cave.
11An Example of a Class - Karel the Robot
- Karel the Robot
- Hidden data
- location
- number of Things
- Interface
- move, turnLeft
- pickThing, putThing
12Modeling a Robot
- Identify key features of the real world object
- Create a class diagram (UML)
- Define attributes and services for a class
- a.k.a. instance variables and methods
13Multiple Instances of a Class
- No limit to the number of objects that can be
created from a class - Each object is independent. Changing one object
doesnt change the others
14Interaction Among Classes
- A program is composed of multiple classes
- Classes may contain references to objects
constructed from other classes within the set of
attributes or behaviours - Start in an application class (main)
- construct one or more objects and call methods
associated with those objects - Three ways to connect multiple classes
- .class files contained in the same location
- import files from libraries
- set up classpath to location of .class files
15Karels World
avenue
City
Robot
Thing
street
Wall
16Simple Java Programs - Start with a main method
- Write a main method to solve a particular problem
- Construct objects
- Call methods
- Use basic control structures
- Needs to be contained in a class
- could be in a separate file - an application
class - could be used for testing a new kind of object -
a template class
17Pattern for a Java Application
May import one or more packages
- import ltltimportedPackagegtgt
- public class ltltClassNamegtgt extends Object
-
- public static void main(String args)
-
- ltlt list of statements to be executedgtgt
-
ClassName is a name you choose, file must be
saved as ClassName.java
For Example import becker.robots. public class
RobotPattern extends Object public static
void main(String args)
Application must have a main method with this
signature, for Java to know where to
start. (Remember that there may be several files
that compose your program.)
18Pattern for Instantiating an Object
runs the constructor method to assign values to
objects instance variables and assign a value to
the reference
- ltltvariableTypegtgt ltltobjectNamegtgt
- ltltobjectNamegtgt new ltltClassNamegtgt(ltltparametersgtgt)
- Or, on one line
- ltltvariableTypegtgt ltltobjectNamegtgt new
ltltClassNamegtgt(ltltparametersgtgt) - For Example
- Robot karel
- karel new Robot (waterloo, 1, 5,
Direction.EAST) - Or
- Robot karel new Robot (waterloo, 1, 5,
Direction.EAST)
Allocate space for a reference to the object
19Pattern for Calling an Objects Method
ltltobjectNamegtgt.ltltmethodNamegtgt(ltltparametersgtgt) Fo
r Example karel.move() Other methods a Robot
can perform include turnLeft(), pickThing(),
putThing(), frontIsClear() A complete list of
methods and their descriptions can be found at
http//www.learningwithrobots.com/doc/
Dot between object and method
Method always followed by ( ), which may or may
not contain parameters
20Putting the Patterns Together
- import becker.robots.
- public class RobotPattern extends Object
- public static void main(String args)
- City mississauga new City("mississauga.txt")
- Robot karel new Robot(mississauga, 1, 2,
Direction.SOUTH) - int side 0
- while (side lt 4)
- while (karel.frontIsClear())
-
- karel.move()
- karel.pickThing()
- // end while isClear
- karel.turnLeft ()
- side
- // end while side
- karel.move()
-
21Inheritance For Example Making a Smarter Robot
- Solving problems with a regular Robot can become
tedious - Inheritance allows programmers to add more
features - Additional methods
- Overloading and overriding methods
- Example turnAround()
- Additional instance variables
- Example Create a new kind of robot that keeps
track of how many steps it has taken - Why inheritance?
- Take advantage of existing code
- If it aint broke
- May not have access to source code
22Pattern for a new Method
public ltltreturnTypegtgt ltltmethodNamegtgt(ltltparameterLi
stgtgt) ltlt list of statements to
executegtgt For Example public int
countThings() int count 0 while
(this.canPickThing())
this.pickThing() count for (int
i0 i lt count i) this.putThing()
return count
returnType may be any Java primitive variable
type (int, boolean, etc) or class, which is
returned by the method, or void
Access may be public (available to any class in
your program) or private (available only to
objects of this class)
When calling another method inside the class, you
can use the implicit parameter this to make the
call.
23Overloading Methods
- Overloading a method means to create a new method
with the same name as an existing method, but
with a different list of parameters. - Example
- move() is a method in the Robot class
- define a new method move(int steps) that has a
parameter that allows us to dictate how many
steps to move - we say the move method is now overloaded
- Note we can invoke either of the move methods we
wish, because Java distinguishes between them by
the parameter list
24An Extended Class RobotSE
- Clearly there are some methods that would be
useful in multiple problems - turnRight()
- move(int steps)
- RobotSE (Special Edition) contains a set of
utility methods
25Inheritance Terminology
- Class one above
- Parent class, Super class
- Class one below
- Child class
- Class one or more above
- Ancestor class, Base class
- Class one or more below
- Descendent class
26Adding Instance variables to the Robot and
Overriding a Method
27An Inheritance Hierarchy
Polymorphism A call to the same method name will
react differently depending upon the object that
calls the method.
Overriddenversion of themove method
28Pattern for Instance Variables
- An instance variable is a variable defined in a
class which is global to all methods in the class - Declared inside the class but outside any methods
in the class - Each object (instance) created from the class has
its own copy of the instance variables - Instance variables should be declared private
- private ltltvariableTypegtgt ltltvariableNamegtgt
ltltinitialValuegtgt - variableType may be any primitive type of
variable or a class - initialValue is optional
- instance variables are often initialized in the
constructor method - instance variables values are accessed
indirectly by calls to public methods, ensuring
encapsulation
29Overriding Methods
- Overriding methods replace the definition of an
existing method, inherited from a parent class - This is accomplished by writing a method
definition with an identical method signature to
the method signature in the parent class - method signature is the method name and parameter
list - you can call the parents method, if needed, by
use of the super keyword - For Example (a paranoid robot)
- public void move()
-
- this.turnLeft() // look both ways before
moving - this.turnRight(2)
- this.turnLeft()
- super.move()
-
30Resources
- Becker Robots (Documentation Downloads)http//w
ww.learningwithrobots.com - Sun Java Class Documentation
- http//java.sun.com/j2se/1.5.0/docs/api/index
.html - Sun Java Tutorials
- http//java.sun.com/developer/onlineTraining/
- Mike Devoys ICS4M course
- http//doyle.wcdsb.edu.on.ca/ICS4MI/index.htm
31Conclusion
- OOP is a useful skill for students
- There is a lot of overhead in programming in an
object-oriented language like Java - Students must learn patterns before they learn
all of the details of the syntax to make early
programs work - OO concepts such as inheritance and polymorphism
can be demonstrated and practiced