26
OOP OOP (Object Oriented Programming (Object Oriented Programming with AS3) with AS3) Flash ActionScript Flash ActionScript 3.0 3.0 Introduction to Introduction to Thomas Lövgren, Flash developer [email protected] Introduction to Introduction to

OOP (Object Oriented Programming with AS3)

  • Upload
    dore

  • View
    76

  • Download
    4

Embed Size (px)

DESCRIPTION

Introduction to. Flash ActionScript 3.0. OOP (Object Oriented Programming with AS3). Introduction to. Thomas Lövgren, Flash developer [email protected]. Introduction to OOP. Lecture Outline In this lecture we’ll discuss and practice the following topics: - PowerPoint PPT Presentation

Citation preview

Page 1: OOP  (Object Oriented Programming with AS3)

OOPOOP (Object Oriented Programming (Object Oriented Programming

with AS3)with AS3)

Flash ActionScript Flash ActionScript 3.03.0

Introduction toIntroduction to

Thomas Lövgren, Flash developer

[email protected]

Introduction toIntroduction to

Page 2: OOP  (Object Oriented Programming with AS3)

Introduction to OOPIntroduction to OOP Lecture OutlineLecture Outline

In this lecture we’ll discuss and practice the following In this lecture we’ll discuss and practice the following topics:topics: OOP: Introduction, Planning & DesignOOP: Introduction, Planning & Design Classes and ObjectsClasses and Objects PropertiesProperties ConstructorConstructor Create a Class file/test itCreate a Class file/test it Parameters and get/set methodsParameters and get/set methods Encapsulation Encapsulation InheritanceInheritance PolymorphismPolymorphism Examples of OOP usageExamples of OOP usage

Page 3: OOP  (Object Oriented Programming with AS3)

Introduction to OOPIntroduction to OOP What is OOP? What is OOP? Object Oriented Programming is Object Oriented Programming is

programming which is oriented around objects, thus programming which is oriented around objects, thus taking advantage of taking advantage of EncapsulationEncapsulation, , PolymorphismPolymorphism, and , and InheritanceInheritance to increase code reuse and decrease code to increase code reuse and decrease code maintenancemaintenance

Why OOP? Why OOP? As applications grow, structured programming As applications grow, structured programming gets unwieldy, and you'll be best advised to use an Object gets unwieldy, and you'll be best advised to use an Object Oriented approachOriented approach

When should I use Object Oriented? When should I use Object Oriented? There’s no given rule There’s no given rule for this, but in general for large projects, for this, but in general for large projects, specific/advanced tasks, extended functionality/libraries specific/advanced tasks, extended functionality/libraries etc. For small/basic projects it’s probably not worth it, etc. For small/basic projects it’s probably not worth it, cause OOP planning, design and implementation takes cause OOP planning, design and implementation takes timetime

Page 4: OOP  (Object Oriented Programming with AS3)

OOP Planning & DesignOOP Planning & Design OOP is a programming paradigm where we can OOP is a programming paradigm where we can

plan, design and use abstraction to create plan, design and use abstraction to create models based on the real worldmodels based on the real world

The object-oriented program design involves:The object-oriented program design involves: Identifying the components of the system or Identifying the components of the system or

application that you want to buildapplication that you want to build Analyzing and identifying patterns to Analyzing and identifying patterns to

determine what components are used determine what components are used repeatedly or share characteristicsrepeatedly or share characteristics

Classifying components based on similarities Classifying components based on similarities and differencesand differences

Page 5: OOP  (Object Oriented Programming with AS3)

Classes & ObjectsClasses & Objects The concept of Classes and Objects is an important part The concept of Classes and Objects is an important part

in AS3, basically the whole in AS3, basically the whole language package language package is based on is based on various classes various classes

So, what is a Class? What is an object?So, what is a Class? What is an object? A class is a self-contained description for a set of services A class is a self-contained description for a set of services

and dataand data The class describes the final product (House). The class describes the final product (House). To actually do something we need an Object (House Object)To actually do something we need an Object (House Object) If the class is the House-blueprint, then the Object is the If the class is the House-blueprint, then the Object is the

HouseHouse We can write one class, and create as many Objects as we We can write one class, and create as many Objects as we

want from that class (with unique properties)want from that class (with unique properties) Objects are often referred to as Class InstancesObjects are often referred to as Class Instances

Page 6: OOP  (Object Oriented Programming with AS3)

PropertiesProperties PropertiesProperties are a collection of are a collection of attributesattributes that that

describes an object describes an object For exampleFor example, an Apple can , an Apple can have properties like color, size and positionhave properties like color, size and position

In a In a ClassClass file, properties are variables/attributes file, properties are variables/attributes that we can access and manipulate, like: that we can access and manipulate, like: var var xPos:Number = 200;xPos:Number = 200;

xPos = 200yPos = 200

Height = 300

Color = red

Page 7: OOP  (Object Oriented Programming with AS3)

Create a New Create a New Object/InstansObject/Instans

(Properties & methods)(Properties & methods) Here is an example of how we can create a new Here is an example of how we can create a new

DogDog Object from the Dog class Object from the Dog class From the Dog class we can create as many new From the Dog class we can create as many new

Dog Objects/Instnaces (with unique properties) Dog Objects/Instnaces (with unique properties) A A Base class Base class (top level class), is also called (top level class), is also called Super Super

classclass

Page 8: OOP  (Object Oriented Programming with AS3)

Packages & Class PathsPackages & Class Paths Packages Packages are folder namespaces where we can are folder namespaces where we can

store our classes, and give them an unique store our classes, and give them an unique identifier – we can use them to sort classes by identifier – we can use them to sort classes by function and make the import of classes easierfunction and make the import of classes easier

Sometimes we need to import external classes, Sometimes we need to import external classes, for the Tween class package in Flash CS3 it looks for the Tween class package in Flash CS3 it looks like this:like this:import fl.transitions.Tween;import fl.transitions.Tween;

import fl.transitions.TweenEvent;import fl.transitions.TweenEvent;

import fl.transitions.easing.*;import fl.transitions.easing.*;

The The class path class path is made up of your domain name is made up of your domain name in reverse (this makes sure that the class path is in reverse (this makes sure that the class path is unique), for example like: unique), for example like: com.interactiondesign.data com.interactiondesign.data

Page 9: OOP  (Object Oriented Programming with AS3)

ConstructorConstructor A A ConstructorConstructor is a is a public public method that has the same method that has the same

name as our class (definens our class) and is used to name as our class (definens our class) and is used to create new instances of our class (by using the create new instances of our class (by using the newnew keyword) keyword)

Any code that we include in our Constructor method is Any code that we include in our Constructor method is executed when a new instance of the class is createdexecuted when a new instance of the class is created

ExampleExample of a Constructor for the class of a Constructor for the class BallBall

//example of a constructor//example of a constructor

public function Ball():void{public function Ball():void{

trace(“Ball constructor in the Ball class“);trace(“Ball constructor in the Ball class“);

}}

NoteNote! If we don’t define a constructor method in our class, the ! If we don’t define a constructor method in our class, the compiler will automatically create an empty constructor for uscompiler will automatically create an empty constructor for us

Page 10: OOP  (Object Oriented Programming with AS3)

EncapsulationEncapsulation((Hiding the detailsHiding the details))

EncapsulationEncapsulation allows us to hide class properties and methods allows us to hide class properties and methods from other areas of our project, but still allows us to manipulate from other areas of our project, but still allows us to manipulate them in a controlled way (classes hide their own internal data)them in a controlled way (classes hide their own internal data)

An An Access modifier Access modifier is a modifier that changes the visibility of a is a modifier that changes the visibility of a class or its members (variables, functions etc) class or its members (variables, functions etc)

In AS3 there are four different Access modifiers:In AS3 there are four different Access modifiers: Public: Public: The public modifier provides access to external members The public modifier provides access to external members Private: Private: The private members are not exposed to external, instances or The private members are not exposed to external, instances or

extended classesextended classes Protected: Access from sub-classesProtected: Access from sub-classes Internal: Internal: Public to classes in same packagePublic to classes in same package

Note! Note! In this lecture we are going to focus on the Public and the Private In this lecture we are going to focus on the Public and the Private modifiermodifier

Page 11: OOP  (Object Oriented Programming with AS3)

Create The Class fileCreate The Class file First, in the Flash Main menu we select First, in the Flash Main menu we select New ActionScript file New ActionScript file

(.as)(.as) The The PackagePackage Keyword in the class file is a mandatory structure Keyword in the class file is a mandatory structure

that ensures that our class file is known to the compilerthat ensures that our class file is known to the compiler

package{ package{ //define package//define package

import flash.display.MovieClip; import flash.display.MovieClip; //import movieclip class//import movieclip class

public class Ball extends MovieClip{ public class Ball extends MovieClip{ //define our class//define our class

//constructor for our class//constructor for our class

public function Ball():void{ public function Ball():void{

trace("Ball class created!"); trace("Ball class created!"); //output//output

}}

}}

} } //end package/class//end package/class

Page 12: OOP  (Object Oriented Programming with AS3)

Testing The Class fileTesting The Class file Create a new Flash AS3 File Create a new Flash AS3 File In the Main Timeline, write the following code:In the Main Timeline, write the following code:

var ball_mc:Ball = new Ball();var ball_mc:Ball = new Ball(); //create a new ball object //create a new ball object

addChild(ball_mc); addChild(ball_mc); //add to displaylist//add to displaylist

trace(ball_mc); trace(ball_mc); //traces "Ball class created!" //traces "Ball class created!"

Note! Note! The Ball class has only one method, containing the The Ball class has only one method, containing the trace-commandtrace-command

Page 13: OOP  (Object Oriented Programming with AS3)

Adding a Symbol Adding a Symbol InstanceInstance

(add/attach a MovieClip to our (add/attach a MovieClip to our class)class) If we want to add/If we want to add/connectconnect a MovieClip to a MovieClip to

our Ball class it could be done like this:our Ball class it could be done like this:

1. Create a MovieClip and give it the name 1. Create a MovieClip and give it the name

ball_mcball_mc

2. Right Click on the ball_mc in Library, 2. Right Click on the ball_mc in Library,

select select Linkage Linkage (properties in CS4)(properties in CS4)

3. Then check the box3. Then check the box

“ “Export for ActionScript”Export for ActionScript”

4. Now the MovieClip is 4. Now the MovieClip is connectedconnected to our to our

Ball class and will automatically be attached from library on Ball class and will automatically be attached from library on startupstartup

Page 14: OOP  (Object Oriented Programming with AS3)

Instance ParametersInstance Parameters(create new objects with unique (create new objects with unique

properties)properties) We can also create new Objects with unique We can also create new Objects with unique

properties, by sending parameters to the class properties, by sending parameters to the class constructor, part of the code looks like this:constructor, part of the code looks like this:

//a part of the class file (Ball.as)//a part of the class file (Ball.as)

//constructor for the Ball class, takes 3 parameters//constructor for the Ball class, takes 3 parameters

public function Ball(xPos:Number, yPos:Number, scale:Number):void{public function Ball(xPos:Number, yPos:Number, scale:Number):void{

x = xPos;x = xPos;

y = yPos;y = yPos;

scaleX = scaleY = scale;scaleX = scaleY = scale;

}}

__________________________________________________________________________________________

//in the main timeline (.fla file)//in the main timeline (.fla file)

//create a new ball object, send 3 parameters to constructor//create a new ball object, send 3 parameters to constructor

var ball_mc:Ball = new Ball(200, 150, 2.5);var ball_mc:Ball = new Ball(200, 150, 2.5);

addChild(ball_mc); addChild(ball_mc); //add to display list//add to display list

Page 15: OOP  (Object Oriented Programming with AS3)

Get and Set MethodsGet and Set Methods(class file)(class file)

Get and Set Methods Get and Set Methods (getters and setters) can be (getters and setters) can be used to access properties or/and set new properties used to access properties or/and set new properties after an Object has been createdafter an Object has been created

//in class file (Ship.as), get and set methods for speed//in class file (Ship.as), get and set methods for speed

public function getSpeed():Number{public function getSpeed():Number{

return _speed; return _speed; //return speed//return speed

}}

public function setSpeed(speed:Number):void{public function setSpeed(speed:Number):void{

_speed = speed; _speed = speed; //set new value//set new value

} }

__________________________________________________________________________________________

//in the main timeline (.fla file)//in the main timeline (.fla file)

//create a new ship object with speed 200//create a new ship object with speed 200

var ship:Ship = new Ship(200);var ship:Ship = new Ship(200);

ship.getSpeed(); ship.getSpeed(); //traces 200//traces 200

ship.setSpeed(350);ship.setSpeed(350);

ship.getSpeed(); ship.getSpeed(); //traces 350//traces 350

Page 16: OOP  (Object Oriented Programming with AS3)

Document ClassDocument Class The The Document class Document class is a new feature in AS3, it’s basically a is a new feature in AS3, it’s basically a

main class, that serves as an application entry point for our main class, that serves as an application entry point for our FLA/SWFFLA/SWF

When SWF’s loaded, the When SWF’s loaded, the ConstructorConstructor of the Document class of the Document class will be calledwill be called

A Document class A Document class extendsextends Sprite or MovieClip class Sprite or MovieClip class In the properties panel in the FLA file, we can define our In the properties panel in the FLA file, we can define our

Document ClassDocument Class

NoteNote! This means that we ! This means that we necessarily necessarily don’t need any code in the main don’t need any code in the main timeline in our FLA filetimeline in our FLA file

Page 17: OOP  (Object Oriented Programming with AS3)

Inheritance (1/2)Inheritance (1/2)((Avoid rebuilding the wheelAvoid rebuilding the wheel))

With With InheritanceInheritance a class can inherit or extend a class can inherit or extend properties and methods from another class (unless properties and methods from another class (unless the properties and methods are marked as private)the properties and methods are marked as private)

The The Subclass Subclass (class that’s inherit), can also add (class that’s inherit), can also add additional properties and/or methods, change some additional properties and/or methods, change some of the ones from the of the ones from the super/baseclasssuper/baseclass (the class (the class that’s being extended)that’s being extended)

The subclass can send received parameters up to The subclass can send received parameters up to the superclass, by using the the superclass, by using the super() super()

command/method and also override inherited command/method and also override inherited methods from the superclass by using the methods from the superclass by using the overrideoverride keywordkeyword

Page 18: OOP  (Object Oriented Programming with AS3)

Inheritance (2/3)Inheritance (2/3)((Avoid rebuilding the wheelAvoid rebuilding the wheel))

In this example we have two classes: A superclass In this example we have two classes: A superclass called called MySuperClassMySuperClass (see below) and a subclass (see below) and a subclass called called MySubClassMySubClass - which inherit properties and - which inherit properties and methods from the superclassmethods from the superclass

package{ package{ //set up the superclass//set up the superclass

public class MySuperClass{ public class MySuperClass{ //declare class//declare class

public function sayHello():void{ public function sayHello():void{ //method//method

trace("Hello from MyBaseClass"); trace("Hello from MyBaseClass"); //output//output

}}

}}

}}

//first frame in main timeline//first frame in main timeline

var sub:MySubClass = new MySubClass(); var sub:MySubClass = new MySubClass(); //create a new subclass object//create a new subclass object

sub.sayHello(); sub.sayHello(); //call derived method from superclass//call derived method from superclass

sub.sayGoodbye(); sub.sayGoodbye(); //call method in subclass//call method in subclass

Page 19: OOP  (Object Oriented Programming with AS3)

Inheritance (3/3)Inheritance (3/3)((Avoid rebuilding the wheelAvoid rebuilding the wheel))

If a class is derived from more than one superclass, If a class is derived from more than one superclass, the inheritance is called: the inheritance is called: Multiple Inheritance Multiple Inheritance – If a – If a class is derived from a derived class, it’s called: class is derived from a derived class, it’s called: Multilevel InheritanceMultilevel Inheritance

Page 20: OOP  (Object Oriented Programming with AS3)

Drawing/Graphics Drawing/Graphics (Sprite)(Sprite)

(Circle Drawing class)(Circle Drawing class) The constructor in this class takes one parameter (radius) The constructor in this class takes one parameter (radius)

and then draws a circle, part of the code looks like this:and then draws a circle, part of the code looks like this:package{package{

import flash.display.Sprite;import flash.display.Sprite;

public class DrawCircle extends Sprite{public class DrawCircle extends Sprite{

private var circle:Sprite;private var circle:Sprite;

private var _radius:Number;private var _radius:Number;

public function DrawCircle(radius:Number):void{public function DrawCircle(radius:Number):void{

_radius = radius;_radius = radius;

circle = new Sprite();circle = new Sprite();

addChild(circle);addChild(circle);

circle.graphics.beginFill(0xff0000);circle.graphics.beginFill(0xff0000);

circle.graphics.drawCircle(300, 100, _radius);circle.graphics.drawCircle(300, 100, _radius);

circle.graphics.endFill();circle.graphics.endFill();

//more code here…//more code here…

Page 21: OOP  (Object Oriented Programming with AS3)

PolymorphismPolymorphism((Exhibiting similar featuresExhibiting similar features))

PolymorphismPolymorphism allows related classes to have allows related classes to have methods that share the same name, but that methods that share the same name, but that behave differently when invokedbehave differently when invoked

By using polymorphism we can reduce the By using polymorphism we can reduce the number of methods for our subclasses, which number of methods for our subclasses, which makes it easier to extend classesmakes it easier to extend classes

Page 22: OOP  (Object Oriented Programming with AS3)

UML DiagramUML Diagram UML Diagram is ideal for software engineers and UML Diagram is ideal for software engineers and

software designers who need to draw detailed software designers who need to draw detailed software design documentationsoftware design documentation

Page 23: OOP  (Object Oriented Programming with AS3)

The Tween ClassThe Tween Class(example of OOP usage)(example of OOP usage)

The Tween class can be used for animations, in this The Tween class can be used for animations, in this case we only have to write 5 lines of code (someone case we only have to write 5 lines of code (someone have programmed the OOP part for us)have programmed the OOP part for us)

So, to get this working, we only have to write like:So, to get this working, we only have to write like:

//import classes//import classes

import fl.transitions.Tween;import fl.transitions.Tween;

import fl.transitions.TweenEvent;import fl.transitions.TweenEvent;

import fl.transitions.easing.*;import fl.transitions.easing.*;

//create the tween object, set up parameters//create the tween object, set up parameters

var myTween:Tween = new Tween(my_mc, "x", Elastic.easeOut, 30, 350, 3, var myTween:Tween = new Tween(my_mc, "x", Elastic.easeOut, 30, 350, 3, true);true);

myTween.start(); myTween.start(); //start tween//start tween

Page 24: OOP  (Object Oriented Programming with AS3)

Flash and PhidgetsFlash and Phidgets(example of OOP usage)(example of OOP usage)

As a Interaction Designer you’ll probably As a Interaction Designer you’ll probably sometimes get in contact with Flash and sometimes get in contact with Flash and Phidigets (sensors)Phidigets (sensors)

AS3 has a great OOP based library for AS3 has a great OOP based library for controlling differnet types of Phidgetscontrolling differnet types of Phidgets

//create a new interface object//create a new interface object

var phid:PhidgetInterfaceKit = new PhidgetInterfaceKit();var phid:PhidgetInterfaceKit = new PhidgetInterfaceKit();

//add listeners to object, call onConnect method//add listeners to object, call onConnect method

phid.addEventListener(PhidgetEvent.CONNECT,phid.addEventListener(PhidgetEvent.CONNECT, onConnect);onConnect);

phid.open("localhost", 5001, "", 65472); phid.open("localhost", 5001, "", 65472); //open connection//open connection

Page 25: OOP  (Object Oriented Programming with AS3)

Game developmentGame development(example of OOP usage)(example of OOP usage)

It’s common to use OOP in Flash-based It’s common to use OOP in Flash-based game game developmentdevelopment, for example a Space Game could , for example a Space Game could have classes like:have classes like: SpaceshipSpaceship EnemiesEnemies BulletBullet ScoreScore

Page 26: OOP  (Object Oriented Programming with AS3)

Summary: Benefits of Summary: Benefits of OOPOOP

Analyzing user requirements Analyzing user requirements Designing software Designing software Constructing software Constructing software

Reusability (reusable components) Reusability (reusable components) Reliability Reliability Robustness Robustness Extensibility Extensibility Maintainability Maintainability

Reduces large problems to smaller, more manageable ones Reduces large problems to smaller, more manageable ones Fits the way the real world works. It is easy to map a real Fits the way the real world works. It is easy to map a real

world problem to a solution in OOP code world problem to a solution in OOP code