SlideShare a Scribd company logo
1 of 53
______________________________________________________________________________________
SCHOOL OF INTERACTIVE ARTS + TECHNOLOGY [SIAT] | WWW.SIAT.SFU.CA
IAT 334
OO programming
IAT 334 1
Outline
 Object-oriented programming
– objects
– classes
• sets (mutators) and gets (accessors)
• object methods
– Inheritance: Subclasses
• Rocket, ArmedRocket
 Collections
– ArrayList
June 22, 2010 IAT 334 2
June 22, 2010 IAT 334 3
Parts of a class
 Classes define fields, constructors and methods
 Fields are the variables that will appear inside every
instance of the class
– Each instance has its own values
 Constructors are special methods that define how to
build instances (generally, how to set the initial values
of fields)
 Methods are how you do things to instances
June 22, 2010 IAT 334 4
Defining the rocket class
class Rocket
{
// fields
float rotation = 0;
float xPos;
float yPos;
final int halfWidth = 10;
final int halfHeight= 10;
// constructor
Rocket( int initialX, int initialY, float initialRot )
{
xPos = initialX;
yPos = initialY;
rotation = initialRot;
}
}
June 22, 2010 IAT 334 5
Using the class to create instances
 Classes define a type
 You can now declare variables of this type and initialize them using
the constructor
 Like arrays, the keyword new is used to tell Java to create a new
object
Rocket r1, r2 ;
void setup() {
r1 = new Rocket(75, 10, 0);
r2 = new Rocket(50, 50, PI/2);
}
 Nice, but my rockets don’t do anything (need methods!)
June 22, 2010 IAT 334 6
Adding a draw routine to our Rocket
void draw() {
pushMatrix();
translate(xPos, yPos);
rotate(rotation);
triangle(0, -halfHeight, -halfWidth, halfHeight,
halfWidth, halfHeight);
rectMode(CORNERS);
rect(-halfWidth + 5, halfHeight, -halfWidth + 8,
halfHeight + 3);
rect(halfWidth - 8, halfHeight, halfWidth - 5,
halfHeight + 3);
popMatrix();
}
Don’t need arguments because we use the fields
But we could define additional arguments if we wanted to
No Arguments!
June 22, 2010 IAT 334 7
Calling methods on objects
 You call methods on instances
 Think of the method as something you are asking the
object to do
 For example, we can now ask the rockets to draw
themselves
r1.draw();
 In general, to call a method, take the name of the
variable holding the object + “.” + the method name
myObject.myMethod();
Objects
June 22, 2010 IAT 334 8
Real Objects
 Real-world objects have
– State
– Behavior
 Bicycle
– State
• selected gear, current pedal cadence, speed
– Behavior
• Change Gear, Set Cadence, Apply Brakes
June 22, 2010 IAT 334 9
Software Object
 State
int gear ;
float speed ;
float cadence ;
 Behavior
ChangeGears(int g);
Brake( float level );
ChangeCadence( float c );
int GetGear();
float GetSpeed(); …
June 22, 2010 IAT 334 10
Java directly supports Objects
 Java has direct syntactic and semantic support for Objects
Syntax:
class Bicycle
{
private int cadence = 0;
private int speed = 0;
private int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
}
IAT 334 11
Java directly supports Objects
 Java has direct syntactic and semantic support for Objects
Semantics:
class Bicycle
{
private int cadence = 0;
private int speed = 0;
private int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
}
IAT 334 12
Only these methods
can read or write
Bicycle private data
Java Semantic support
 Programming usually takes place with
objects:
ClockThing clock = new ClockThing();
clock.setSecond( 12 );
clock.setMinute( 18 );
clock.setHour( 3 );
June 22, 2010 IAT 334 13
Even Arrays are objects
int[] bob = new int[10] ;
bob[4] = 123 ;
println( bob.size() );
Bicycle[] bikes = new Bicycle[10] ;
bikes[0] = new Bicycle();
June 22, 2010 IAT 334 14
Sets and Gets
 what can you do with private data?
– to set it: setVarName( varType newValue)
– to get it: varType getVarName()
 Why?
June 22, 2010 IAT 334 15
Temperature object
class temp
{
private float kelvin ;
setCelsius( float C );
{ if( C < -273.15 )
return ; // perhaps an error message would be in order
else
kelvin = C + 273.15 ;
}
float getCelsius()
{ return( kelvin - 273.15 );
}
float setKelvin( float k )
{ if( k < 0 )
return ;
else
kelvin = k ;
}
}
IAT 334 16
Temperature object
 Controls access
 Ensures correctness
– can only run a setXYZ() to change temp
– can only do getXYZ() to get the value in the
desired scale
 Who cares?
June 22, 2010 IAT 334 17
Who cares?
 When you want to:
– Solve the problem once and forget it
– Reuse the solution elsewhere
– Establish rules for use and change of data
 The principle:
– Information hiding
– By interacting only with an object's methods, the
details of its internal implementation remain hidden
from the outside world.
June 22, 2010 IAT 334 18
Principle: Code re-use
 If an object already exists, you can use
that object in your program.
 Specialists build, you use
June 22, 2010 IAT 334 19
Principle: Define the Interface
 Define the interface:
– The list of methods with Defined Operation
 The interface is the thing that other people
use
 If you have the same interface with the
same meaning
– You can plug in a better implementation!
June 22, 2010 IAT 334 20
Define the Interface
 If you have the same interface with the
same meaning
– You can plug in a better implementation!
– You can plug in a More Interesting
implementation!
June 22, 2010 IAT 334 21
Summary of principles
 Hide unnecessary details
 Clearly define the interface
 Allow and support code re-use
 Build on the work of others
June 22, 2010 IAT 334 22
Inheritance
June 22, 2010 IAT 334 23
Classes
 Types
– Primitives: int, float, char, boolean …
– Objects: array, string, class …
June 22, 2010 IAT 334
Objects
 We’ve worked with some objects before,
like Arrays.
 We can make our own objects, to keep
related data together, with methods to
control that data.
June 22, 2010 IAT 334
Classes
 Classes are the blueprints for our new
objects.
 To declare a new Class (a new type of
object):
June 22, 2010 IAT 334
class MyToy {
// fields (class variables)
// methods (class functions)
}
Fields and Methods
June 22, 2010 IAT 334
class MySquare {
int xPos, yPos;
MySquare(x, y) {
xPos = x;
yPos = y;
}
void drawMe() {
rect(xPos, yPos, 50, 50);
}
}
x y
drawMe()
fields
constructor
methods
(one kind
of method)
Fields and Methods
June 22, 2010 IAT 334
class MySquare {
int xPos, yPos;
MySquare(x, y) {
xPos = x;
yPos = y;
}
void drawMe() {
rect(xPos, yPos, 50, 50);
}
}
x y
drawMe()
MySquare square1 = new MySquare(10, 10);
MySquare square2 = new MySquare(20, 90);
10 10
drawMe()
20 90
drawMe()
square1 square2
Fields and Methods
June 22, 2010 IAT 334
class MySquare {
int xPos, yPos;
MySquare(int x, int y) {
xPos = x;
yPos = y;
}
void drawMe() {
rect(xPos, yPos, 50, 50);
}
}
MySquare square1 = new MySquare(10, 10);
MySquare square2 = new MySquare(20, 90);
x y
drawMe()
10 10
drawMe()
20 90
drawMe()
square1 square2
square1.drawMe();
square2.drawMe();
Arrays of Objects?
 Let’s make a bunch of squares!
June 22, 2010 IAT 334
MySquare[] squares = new MySquare [10] ;
// initialize all of our squares.
for (int i = 0; i < 10; i ++) {
squares[i] = new MySquare(i*10, i*10);
}
squares[4].drawMe(); // draw the 4th square.
Recap: Rocket
 In Lab 2, we created the Rocket class
– Constructor:
Rocket(int initialX, int initialY, float initialRot )
– Methods
draw()
rotateClockwise()
rotateCounterClockwise()
fireThrusters()
June 22, 2010 IAT 334
Asteroids
 Let’s adapt this to make an array of
Asteroids for our rocket from Lab 2
June 22, 2010 IAT 334
class Asteroid {
//fields
float rotation = 0;
float xPos, yPos;
float velocityX, velocityY;
long lastDrawMillis = 0;
…
}
Asteroids
 When we create an asteroid, let’s have it
start in a random position, and move in a
random direction.
June 22, 2010 IAT 334
class Asteroid {
…
// constructor
Asteroid() {
xPos = random(0, 400);
yPos = random(0, 400);
rotation = random(0, TWO_PI);
velocityX = sin(rotation)*10;
velocityY = -cos(rotation)*10;
}
Asteroids
June 22, 2010 IAT 334
class Asteroid {
…
// draw method
void draw () {
Revisit our example
 So far we have a rocket that flies around in a
field of asteroids
 What if we want our rocket to be able to fire
– But we don’t want to get rid of our non-firing rocket
 Create a subclass!
June 22, 2010 IAT 334
Inheritance
 Subclasses inherit fields and methods
from parent
class ArmedRocket extends Rocket {
…
}
June 22, 2010 IAT 334
Our subclass needs a
constructor
 Our empty ArmedRocket example creates an error
– Processing doesn’t know how to construct an ArmedRocket
 We want the ArmedRocket constructor to do the same
work as the Rocket constructor
ArmedRocket(int initialX, int initialY, float initialRot) {
super(initialX, initialY, initialRot);
}
The keyword super means to refer to the parent class.
In this case, to call the Parent Class Constructor
June 22, 2010 IAT 334
Now we have ArmedRocket
 We can use an ArmedRocket now in our
example
 But, it’s basically just a copy of Rocket
 The only reason to define an
ArmedRocket is to add new capabilities or
to override old ones
June 22, 2010 IAT 334
Add a fire() method
 We want our fire method to draw a
missile that shoots out of the rocket
 We could have the fire method draw the
missile…
– Is there a problem with this?
June 22, 2010 IAT 334
Missiles should also be objects
 The object oriented solution is to make the missile an
object as well
– All the different types of “things” in our domain should
have a corresponding class
 Like asteroids and rockets, the missile class should know
how to draw itself
– A Missile is similar to a rocket (position, rotation, draw
method, etc.)
 Now our ArmedRocket.fire() method can just create and
return a missile
June 22, 2010 IAT 334
The fire() method
Missile fire()
{
Missile m = new Missile(xPos, yPos, rotation);
return m;
}
 Now add code in loop to draw missiles
June 22, 2010 IAT 334
Missiles destroy asteroids
 So far we have a rocket that flies around in a
field of asteroids and fires
 Now we want our missiles to blow up asteroids
– This means we need a variable number of asteroids.
– How do we do this with an array?
– Use an ArrayList!
– Also need to figure out when we have a collision
June 22, 2010 IAT 334 42
The Java SDK
 Java comes with thousands of classes in
the Java Platform API
 Documentation is available on Sun’s
website
 Let’s look at ArrayList
June 22, 2010 IAT 334 43
ArrayList
 It’s a resizeable list
– Can add and delete things without worrying about declaring the size
 The main methods we care about are add(), get(), and
remove(), and size()
 Steps in using ArrayList
– Declare a variable of type ArrayList
– Create a new ArrayList and assign it to the variable
– Call add(), get() and remove() and size() on ArrayList as you need
them
June 22, 2010 IAT 334 44
Parents and children
 Remember that we declared a child class ArmedRocket whose parent
was Rocket
 Remember that classes are types
– So ArmedRocket is a type and Rocket is a type
 So, here are some legal assignments
– ArmedRocket r1 = new ArmedRocket(50, 60, 0);
– Rocket r2 = new Rocket(50, 60, 0);
– Rocket r3 = new ArmedRocket(50, 60, 0);
 But this is illegal
– ArmedRocket r4 = new Rocket(50, 60, 0);
 Same goes for method arguments as well…
June 22, 2010 IAT 334 45
Rocket Inheritance
June 22, 2010 IAT 334 46
Rocket:
xPos, YPos, velocityX, velocityY, rotation
Rocket(x,y,rotation) draw()
ArmedRocket extends Rocket
xPos, YPos, velocityX, velocityY, rotation
ArmedRocket(x,y,rotation) draw() fire()
Inherits from
Using ArrayList.add()
 The argument type of the add method is Object
– Object is the parent class of all classes
– With an object argument type, you can pass in an
object of any class
 So, to initialize our asteroids…
ArrayList asteroids = new ArrayList();
for(int i = 0; i < numAsteroids; i++)
asteroids.add(new Asteroid());
June 22, 2010 IAT 334 47
Getting things out of an
ArrayList
 ArrayList.get(int i) – returns the ith object
(starting with 0)
 But this doesn’t work!
asteroids.get(i).draw();
Why?
June 22, 2010 IAT 334 48
Need to cast back from Object
 Since things are put in an ArrayList as Object,
they come back out as Object
– It’s like they forget their more detailed type
– So, when using ArrayList (or any container class),
need to cast back to the more detailed type
Asteroid asteroid = (Asteroid)asteroids.get(i);
if (!asteroid.collision(r1))
asteroid.draw();
June 22, 2010 IAT 334 49
Pushing collision detection
into the Asteroid
 In the current code, detecting collision takes place in loop()
 But it is cleaner (more object-oriented) if Asteroid itself knows how
to detect collision
– Detecting collision depends on knowing the boundaries of the asteroid,
which properly belongs in the asteroid class
boolean collision(Rocket r)
{
if ((r.xPos >= xPos - 26 && r.xPos <= xPos + 22) &&
(r.yPos >= yPos - 24 && r.yPos <= yPos + 26))
return true;
else
return false;
}
June 22, 2010 IAT 334 50
Destroying asteroids
 When a missile hits an Asteroid, we need to destroy it
– This was the whole reason for using ArrayList
– Big asteroids turn into two small asteroids
– Small asteroids disappear
void destroy(ArrayList asteroids) {
asteroids.remove(this);
if (large) {
asteroids.add(new Asteroid(false, xPos, yPos, lastDrawMillis));
asteroids.add(new Asteroid(false, xPos, yPos, lastDrawMillis));
}
}
June 22, 2010 IAT 334 51
Super and this
 this is a special variable that always refers to the
current instance (object)
– Useful in methods to refer to yourself
– this.method() – calls a method on yourself (but normally you just
directly call the method)
– this() – calls a constructor on yourself (useful for one version of a
constructor to call another)
 super is a special variable that always refers to the
superclass portion of an object (the object cast into
it’s superclass)
– super.method() – calls the superclass’s method
– super() – calls the superclass’s constructor
June 22, 2010 IAT 334 52
Summary
 ArrayList, a Java Platform collection class
 Learned about super and subclasses as types
– Any instance of a subclass is an instance of the
superclass, but not visa-versa
– Can cast more abstract classes (parents) into more
concrete classes (children)
 The Java keywords super and this
– Special variables that can be used within a method to
refer to yourself (the superclass portion of yourself and all
of yourself)
June 22, 2010 IAT 334 53

More Related Content

Similar to IAT334-Lec06-OOTutorial.pptx

Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.pptMikeAdva
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaGlenn Guden
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1Daman Toor
 
Class & Objects in JAVA.ppt
Class & Objects in JAVA.pptClass & Objects in JAVA.ppt
Class & Objects in JAVA.pptRohitPaul71
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class StructureHadziq Fabroyir
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object javamha4
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and ClassesIntro C# Book
 

Similar to IAT334-Lec06-OOTutorial.pptx (20)

Java Day-4
Java Day-4Java Day-4
Java Day-4
 
oops-1
oops-1oops-1
oops-1
 
Unit i
Unit iUnit i
Unit i
 
Chap08
Chap08Chap08
Chap08
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Classes1
Classes1Classes1
Classes1
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
Internet programming slide - java.ppt
Internet programming slide - java.pptInternet programming slide - java.ppt
Internet programming slide - java.ppt
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
Lecture3.pdf
Lecture3.pdfLecture3.pdf
Lecture3.pdf
 
Java assignment 1
Java assignment 1Java assignment 1
Java assignment 1
 
Class & Objects in JAVA.ppt
Class & Objects in JAVA.pptClass & Objects in JAVA.ppt
Class & Objects in JAVA.ppt
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Using class and object java
Using class and object javaUsing class and object java
Using class and object java
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 
Object and class
Object and classObject and class
Object and class
 

More from ssuseraae9cd

IAT334-Lec07-Pen.pptx
IAT334-Lec07-Pen.pptxIAT334-Lec07-Pen.pptx
IAT334-Lec07-Pen.pptxssuseraae9cd
 
IAT334-Lec10-Rollup.pptx
IAT334-Lec10-Rollup.pptxIAT334-Lec10-Rollup.pptx
IAT334-Lec10-Rollup.pptxssuseraae9cd
 
IAT334-Lec01-Intro.pptx
IAT334-Lec01-Intro.pptxIAT334-Lec01-Intro.pptx
IAT334-Lec01-Intro.pptxssuseraae9cd
 
IAT334-Lec02-TaskAnalysis.pptx
IAT334-Lec02-TaskAnalysis.pptxIAT334-Lec02-TaskAnalysis.pptx
IAT334-Lec02-TaskAnalysis.pptxssuseraae9cd
 
IAT334-Lec03-Cog+UsabilityPrinciples.pptx
IAT334-Lec03-Cog+UsabilityPrinciples.pptxIAT334-Lec03-Cog+UsabilityPrinciples.pptx
IAT334-Lec03-Cog+UsabilityPrinciples.pptxssuseraae9cd
 
IAT334-Lec05-Dialog.pptx
IAT334-Lec05-Dialog.pptxIAT334-Lec05-Dialog.pptx
IAT334-Lec05-Dialog.pptxssuseraae9cd
 
IAT334-Lec04-DesignIdeasPrinciples.pptx
IAT334-Lec04-DesignIdeasPrinciples.pptxIAT334-Lec04-DesignIdeasPrinciples.pptx
IAT334-Lec04-DesignIdeasPrinciples.pptxssuseraae9cd
 
IAT334-Lec09-Errors+Doc.pptx
IAT334-Lec09-Errors+Doc.pptxIAT334-Lec09-Errors+Doc.pptx
IAT334-Lec09-Errors+Doc.pptxssuseraae9cd
 
IAT334-Lec08-Experiment.pptx
IAT334-Lec08-Experiment.pptxIAT334-Lec08-Experiment.pptx
IAT334-Lec08-Experiment.pptxssuseraae9cd
 
IAT334-Lec07-Models.pptx
IAT334-Lec07-Models.pptxIAT334-Lec07-Models.pptx
IAT334-Lec07-Models.pptxssuseraae9cd
 

More from ssuseraae9cd (10)

IAT334-Lec07-Pen.pptx
IAT334-Lec07-Pen.pptxIAT334-Lec07-Pen.pptx
IAT334-Lec07-Pen.pptx
 
IAT334-Lec10-Rollup.pptx
IAT334-Lec10-Rollup.pptxIAT334-Lec10-Rollup.pptx
IAT334-Lec10-Rollup.pptx
 
IAT334-Lec01-Intro.pptx
IAT334-Lec01-Intro.pptxIAT334-Lec01-Intro.pptx
IAT334-Lec01-Intro.pptx
 
IAT334-Lec02-TaskAnalysis.pptx
IAT334-Lec02-TaskAnalysis.pptxIAT334-Lec02-TaskAnalysis.pptx
IAT334-Lec02-TaskAnalysis.pptx
 
IAT334-Lec03-Cog+UsabilityPrinciples.pptx
IAT334-Lec03-Cog+UsabilityPrinciples.pptxIAT334-Lec03-Cog+UsabilityPrinciples.pptx
IAT334-Lec03-Cog+UsabilityPrinciples.pptx
 
IAT334-Lec05-Dialog.pptx
IAT334-Lec05-Dialog.pptxIAT334-Lec05-Dialog.pptx
IAT334-Lec05-Dialog.pptx
 
IAT334-Lec04-DesignIdeasPrinciples.pptx
IAT334-Lec04-DesignIdeasPrinciples.pptxIAT334-Lec04-DesignIdeasPrinciples.pptx
IAT334-Lec04-DesignIdeasPrinciples.pptx
 
IAT334-Lec09-Errors+Doc.pptx
IAT334-Lec09-Errors+Doc.pptxIAT334-Lec09-Errors+Doc.pptx
IAT334-Lec09-Errors+Doc.pptx
 
IAT334-Lec08-Experiment.pptx
IAT334-Lec08-Experiment.pptxIAT334-Lec08-Experiment.pptx
IAT334-Lec08-Experiment.pptx
 
IAT334-Lec07-Models.pptx
IAT334-Lec07-Models.pptxIAT334-Lec07-Models.pptx
IAT334-Lec07-Models.pptx
 

Recently uploaded

FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Roomishabajaj13
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirtrahman018755
 
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With RoomVIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Roomdivyansh0kumar0
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsstephieert
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceDelhi Call girls
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Delhi Call girls
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...tanu pandey
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girladitipandeya
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$kojalkojal131
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebJames Anderson
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Servicesexy call girls service in goa
 

Recently uploaded (20)

FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
 
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With RoomVIP Kolkata Call Girl Dum Dum 👉 8250192130  Available With Room
VIP Kolkata Call Girl Dum Dum 👉 8250192130 Available With Room
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girls
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Samaira 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Samaira 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 

IAT334-Lec06-OOTutorial.pptx

  • 1. ______________________________________________________________________________________ SCHOOL OF INTERACTIVE ARTS + TECHNOLOGY [SIAT] | WWW.SIAT.SFU.CA IAT 334 OO programming IAT 334 1
  • 2. Outline  Object-oriented programming – objects – classes • sets (mutators) and gets (accessors) • object methods – Inheritance: Subclasses • Rocket, ArmedRocket  Collections – ArrayList June 22, 2010 IAT 334 2
  • 3. June 22, 2010 IAT 334 3 Parts of a class  Classes define fields, constructors and methods  Fields are the variables that will appear inside every instance of the class – Each instance has its own values  Constructors are special methods that define how to build instances (generally, how to set the initial values of fields)  Methods are how you do things to instances
  • 4. June 22, 2010 IAT 334 4 Defining the rocket class class Rocket { // fields float rotation = 0; float xPos; float yPos; final int halfWidth = 10; final int halfHeight= 10; // constructor Rocket( int initialX, int initialY, float initialRot ) { xPos = initialX; yPos = initialY; rotation = initialRot; } }
  • 5. June 22, 2010 IAT 334 5 Using the class to create instances  Classes define a type  You can now declare variables of this type and initialize them using the constructor  Like arrays, the keyword new is used to tell Java to create a new object Rocket r1, r2 ; void setup() { r1 = new Rocket(75, 10, 0); r2 = new Rocket(50, 50, PI/2); }  Nice, but my rockets don’t do anything (need methods!)
  • 6. June 22, 2010 IAT 334 6 Adding a draw routine to our Rocket void draw() { pushMatrix(); translate(xPos, yPos); rotate(rotation); triangle(0, -halfHeight, -halfWidth, halfHeight, halfWidth, halfHeight); rectMode(CORNERS); rect(-halfWidth + 5, halfHeight, -halfWidth + 8, halfHeight + 3); rect(halfWidth - 8, halfHeight, halfWidth - 5, halfHeight + 3); popMatrix(); } Don’t need arguments because we use the fields But we could define additional arguments if we wanted to No Arguments!
  • 7. June 22, 2010 IAT 334 7 Calling methods on objects  You call methods on instances  Think of the method as something you are asking the object to do  For example, we can now ask the rockets to draw themselves r1.draw();  In general, to call a method, take the name of the variable holding the object + “.” + the method name myObject.myMethod();
  • 9. Real Objects  Real-world objects have – State – Behavior  Bicycle – State • selected gear, current pedal cadence, speed – Behavior • Change Gear, Set Cadence, Apply Brakes June 22, 2010 IAT 334 9
  • 10. Software Object  State int gear ; float speed ; float cadence ;  Behavior ChangeGears(int g); Brake( float level ); ChangeCadence( float c ); int GetGear(); float GetSpeed(); … June 22, 2010 IAT 334 10
  • 11. Java directly supports Objects  Java has direct syntactic and semantic support for Objects Syntax: class Bicycle { private int cadence = 0; private int speed = 0; private int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } } IAT 334 11
  • 12. Java directly supports Objects  Java has direct syntactic and semantic support for Objects Semantics: class Bicycle { private int cadence = 0; private int speed = 0; private int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } } IAT 334 12 Only these methods can read or write Bicycle private data
  • 13. Java Semantic support  Programming usually takes place with objects: ClockThing clock = new ClockThing(); clock.setSecond( 12 ); clock.setMinute( 18 ); clock.setHour( 3 ); June 22, 2010 IAT 334 13
  • 14. Even Arrays are objects int[] bob = new int[10] ; bob[4] = 123 ; println( bob.size() ); Bicycle[] bikes = new Bicycle[10] ; bikes[0] = new Bicycle(); June 22, 2010 IAT 334 14
  • 15. Sets and Gets  what can you do with private data? – to set it: setVarName( varType newValue) – to get it: varType getVarName()  Why? June 22, 2010 IAT 334 15
  • 16. Temperature object class temp { private float kelvin ; setCelsius( float C ); { if( C < -273.15 ) return ; // perhaps an error message would be in order else kelvin = C + 273.15 ; } float getCelsius() { return( kelvin - 273.15 ); } float setKelvin( float k ) { if( k < 0 ) return ; else kelvin = k ; } } IAT 334 16
  • 17. Temperature object  Controls access  Ensures correctness – can only run a setXYZ() to change temp – can only do getXYZ() to get the value in the desired scale  Who cares? June 22, 2010 IAT 334 17
  • 18. Who cares?  When you want to: – Solve the problem once and forget it – Reuse the solution elsewhere – Establish rules for use and change of data  The principle: – Information hiding – By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. June 22, 2010 IAT 334 18
  • 19. Principle: Code re-use  If an object already exists, you can use that object in your program.  Specialists build, you use June 22, 2010 IAT 334 19
  • 20. Principle: Define the Interface  Define the interface: – The list of methods with Defined Operation  The interface is the thing that other people use  If you have the same interface with the same meaning – You can plug in a better implementation! June 22, 2010 IAT 334 20
  • 21. Define the Interface  If you have the same interface with the same meaning – You can plug in a better implementation! – You can plug in a More Interesting implementation! June 22, 2010 IAT 334 21
  • 22. Summary of principles  Hide unnecessary details  Clearly define the interface  Allow and support code re-use  Build on the work of others June 22, 2010 IAT 334 22
  • 24. Classes  Types – Primitives: int, float, char, boolean … – Objects: array, string, class … June 22, 2010 IAT 334
  • 25. Objects  We’ve worked with some objects before, like Arrays.  We can make our own objects, to keep related data together, with methods to control that data. June 22, 2010 IAT 334
  • 26. Classes  Classes are the blueprints for our new objects.  To declare a new Class (a new type of object): June 22, 2010 IAT 334 class MyToy { // fields (class variables) // methods (class functions) }
  • 27. Fields and Methods June 22, 2010 IAT 334 class MySquare { int xPos, yPos; MySquare(x, y) { xPos = x; yPos = y; } void drawMe() { rect(xPos, yPos, 50, 50); } } x y drawMe() fields constructor methods (one kind of method)
  • 28. Fields and Methods June 22, 2010 IAT 334 class MySquare { int xPos, yPos; MySquare(x, y) { xPos = x; yPos = y; } void drawMe() { rect(xPos, yPos, 50, 50); } } x y drawMe() MySquare square1 = new MySquare(10, 10); MySquare square2 = new MySquare(20, 90); 10 10 drawMe() 20 90 drawMe() square1 square2
  • 29. Fields and Methods June 22, 2010 IAT 334 class MySquare { int xPos, yPos; MySquare(int x, int y) { xPos = x; yPos = y; } void drawMe() { rect(xPos, yPos, 50, 50); } } MySquare square1 = new MySquare(10, 10); MySquare square2 = new MySquare(20, 90); x y drawMe() 10 10 drawMe() 20 90 drawMe() square1 square2 square1.drawMe(); square2.drawMe();
  • 30. Arrays of Objects?  Let’s make a bunch of squares! June 22, 2010 IAT 334 MySquare[] squares = new MySquare [10] ; // initialize all of our squares. for (int i = 0; i < 10; i ++) { squares[i] = new MySquare(i*10, i*10); } squares[4].drawMe(); // draw the 4th square.
  • 31. Recap: Rocket  In Lab 2, we created the Rocket class – Constructor: Rocket(int initialX, int initialY, float initialRot ) – Methods draw() rotateClockwise() rotateCounterClockwise() fireThrusters() June 22, 2010 IAT 334
  • 32. Asteroids  Let’s adapt this to make an array of Asteroids for our rocket from Lab 2 June 22, 2010 IAT 334 class Asteroid { //fields float rotation = 0; float xPos, yPos; float velocityX, velocityY; long lastDrawMillis = 0; … }
  • 33. Asteroids  When we create an asteroid, let’s have it start in a random position, and move in a random direction. June 22, 2010 IAT 334 class Asteroid { … // constructor Asteroid() { xPos = random(0, 400); yPos = random(0, 400); rotation = random(0, TWO_PI); velocityX = sin(rotation)*10; velocityY = -cos(rotation)*10; }
  • 34. Asteroids June 22, 2010 IAT 334 class Asteroid { … // draw method void draw () {
  • 35. Revisit our example  So far we have a rocket that flies around in a field of asteroids  What if we want our rocket to be able to fire – But we don’t want to get rid of our non-firing rocket  Create a subclass! June 22, 2010 IAT 334
  • 36. Inheritance  Subclasses inherit fields and methods from parent class ArmedRocket extends Rocket { … } June 22, 2010 IAT 334
  • 37. Our subclass needs a constructor  Our empty ArmedRocket example creates an error – Processing doesn’t know how to construct an ArmedRocket  We want the ArmedRocket constructor to do the same work as the Rocket constructor ArmedRocket(int initialX, int initialY, float initialRot) { super(initialX, initialY, initialRot); } The keyword super means to refer to the parent class. In this case, to call the Parent Class Constructor June 22, 2010 IAT 334
  • 38. Now we have ArmedRocket  We can use an ArmedRocket now in our example  But, it’s basically just a copy of Rocket  The only reason to define an ArmedRocket is to add new capabilities or to override old ones June 22, 2010 IAT 334
  • 39. Add a fire() method  We want our fire method to draw a missile that shoots out of the rocket  We could have the fire method draw the missile… – Is there a problem with this? June 22, 2010 IAT 334
  • 40. Missiles should also be objects  The object oriented solution is to make the missile an object as well – All the different types of “things” in our domain should have a corresponding class  Like asteroids and rockets, the missile class should know how to draw itself – A Missile is similar to a rocket (position, rotation, draw method, etc.)  Now our ArmedRocket.fire() method can just create and return a missile June 22, 2010 IAT 334
  • 41. The fire() method Missile fire() { Missile m = new Missile(xPos, yPos, rotation); return m; }  Now add code in loop to draw missiles June 22, 2010 IAT 334
  • 42. Missiles destroy asteroids  So far we have a rocket that flies around in a field of asteroids and fires  Now we want our missiles to blow up asteroids – This means we need a variable number of asteroids. – How do we do this with an array? – Use an ArrayList! – Also need to figure out when we have a collision June 22, 2010 IAT 334 42
  • 43. The Java SDK  Java comes with thousands of classes in the Java Platform API  Documentation is available on Sun’s website  Let’s look at ArrayList June 22, 2010 IAT 334 43
  • 44. ArrayList  It’s a resizeable list – Can add and delete things without worrying about declaring the size  The main methods we care about are add(), get(), and remove(), and size()  Steps in using ArrayList – Declare a variable of type ArrayList – Create a new ArrayList and assign it to the variable – Call add(), get() and remove() and size() on ArrayList as you need them June 22, 2010 IAT 334 44
  • 45. Parents and children  Remember that we declared a child class ArmedRocket whose parent was Rocket  Remember that classes are types – So ArmedRocket is a type and Rocket is a type  So, here are some legal assignments – ArmedRocket r1 = new ArmedRocket(50, 60, 0); – Rocket r2 = new Rocket(50, 60, 0); – Rocket r3 = new ArmedRocket(50, 60, 0);  But this is illegal – ArmedRocket r4 = new Rocket(50, 60, 0);  Same goes for method arguments as well… June 22, 2010 IAT 334 45
  • 46. Rocket Inheritance June 22, 2010 IAT 334 46 Rocket: xPos, YPos, velocityX, velocityY, rotation Rocket(x,y,rotation) draw() ArmedRocket extends Rocket xPos, YPos, velocityX, velocityY, rotation ArmedRocket(x,y,rotation) draw() fire() Inherits from
  • 47. Using ArrayList.add()  The argument type of the add method is Object – Object is the parent class of all classes – With an object argument type, you can pass in an object of any class  So, to initialize our asteroids… ArrayList asteroids = new ArrayList(); for(int i = 0; i < numAsteroids; i++) asteroids.add(new Asteroid()); June 22, 2010 IAT 334 47
  • 48. Getting things out of an ArrayList  ArrayList.get(int i) – returns the ith object (starting with 0)  But this doesn’t work! asteroids.get(i).draw(); Why? June 22, 2010 IAT 334 48
  • 49. Need to cast back from Object  Since things are put in an ArrayList as Object, they come back out as Object – It’s like they forget their more detailed type – So, when using ArrayList (or any container class), need to cast back to the more detailed type Asteroid asteroid = (Asteroid)asteroids.get(i); if (!asteroid.collision(r1)) asteroid.draw(); June 22, 2010 IAT 334 49
  • 50. Pushing collision detection into the Asteroid  In the current code, detecting collision takes place in loop()  But it is cleaner (more object-oriented) if Asteroid itself knows how to detect collision – Detecting collision depends on knowing the boundaries of the asteroid, which properly belongs in the asteroid class boolean collision(Rocket r) { if ((r.xPos >= xPos - 26 && r.xPos <= xPos + 22) && (r.yPos >= yPos - 24 && r.yPos <= yPos + 26)) return true; else return false; } June 22, 2010 IAT 334 50
  • 51. Destroying asteroids  When a missile hits an Asteroid, we need to destroy it – This was the whole reason for using ArrayList – Big asteroids turn into two small asteroids – Small asteroids disappear void destroy(ArrayList asteroids) { asteroids.remove(this); if (large) { asteroids.add(new Asteroid(false, xPos, yPos, lastDrawMillis)); asteroids.add(new Asteroid(false, xPos, yPos, lastDrawMillis)); } } June 22, 2010 IAT 334 51
  • 52. Super and this  this is a special variable that always refers to the current instance (object) – Useful in methods to refer to yourself – this.method() – calls a method on yourself (but normally you just directly call the method) – this() – calls a constructor on yourself (useful for one version of a constructor to call another)  super is a special variable that always refers to the superclass portion of an object (the object cast into it’s superclass) – super.method() – calls the superclass’s method – super() – calls the superclass’s constructor June 22, 2010 IAT 334 52
  • 53. Summary  ArrayList, a Java Platform collection class  Learned about super and subclasses as types – Any instance of a subclass is an instance of the superclass, but not visa-versa – Can cast more abstract classes (parents) into more concrete classes (children)  The Java keywords super and this – Special variables that can be used within a method to refer to yourself (the superclass portion of yourself and all of yourself) June 22, 2010 IAT 334 53