00:00
00:00

As: Oop Classes

4,935 Views | 30 Replies
New Topic Respond to this Topic

As: Oop Classes 2006-01-08 09:47:06


var ASMain:TutorialBank = new TutorialBank();

INTRODUCTION
this tutorial will cover the basics and intermediate levels of OOP class writing. this thread can be considered a disambiguation of inglors AS OOP thread. some assumed knowledge includes variables, functions, basic OOP (prototyping), and it is recommended that you understand class instantiation.

TERMINOLOGY
property - a property is what one would usually refer to as a variable outside of classes. a class stores certain pieces of information, known as properties, as either static or dynamic information. an example of a property would be the MovieClip._x (which is the _x property of the MovieClip class).
method - again, a method is what one would usually refer to as a function outside of classes. a class performs normal actions through these methods. an example of a method would the Math.sin() (which is a sin method of the Math class).

AS: OOP (Object Oriented Programming) by Inglor
AS: Prototype, Proto & Inheritance by BleeBlap

CLASS SYNTAX
for actionscripted OOP classes, the file name must match the name of the class. for instance, if you wanted to create a class called MyFirstClass, the actionscript file must be named MyFirstClass.as (this name is case-sensitive, so capitalization does matter). to use the AS class, you must include the *.as file in the same directory as the FLA in which you intend to use it.

okay, begin by writing out the class delimiters:

class MyFirstClass{
}

PROPERTIES
accesstype var propName:DataType = new DataType();

first thing we want to do is initialize every property we intend to use in the class. any included variable must be given an access-type. the most common are "public" and "private". the public properties can be viewed and changed by any piece of code anywhere at anytime. some examples of public properties would be the _x and _y properties of the MovieClip class.

a private property can only be accessed and modified from a method within the class. an example of this would be the _depth property of the MovieClip class. you can change this with a public method, a process called "encapsulation" which i will cover later, but you cannot change _depth on its own.

so let us decide some properties to add to our class:

public var canTrace:Boolean = true;
public var allCaps:Boolean = false;
private var lastMessage:String = new String();
private var timesSpoken:Number = 0;

METHODS
accesstype function methdName(params:DataType):ReturnType{
}

think of these as glorified functions that are attached to each class and can modify properties. the access type works in the same way as with the properties. a public method can be accessed from any place in any code accompanying the class. an example of a public method is simple. any method youve ever used (swapDepths(), setTransform(), getVolume(), etc).

a private method is only able to be accessed by other methods in the function, and are commonly used just for assisting private methods. these methods essentially are only to be used to streamline reused code.

lets throw in a sample method to this class:

public function sendMessage(msg:String):Void{
if (!canTrace) return;
var curMessage:String = allCaps ? msg.toUpperCase() : msg;
trace(curMessage);
lastMessage = curMessage;
timesSpoken++;
}

CONSTRUCTOR METHOD
the constructor is the method that is called immediately when the class is instantiated. the requirements are that the constructor have the EXACT same name as the class itself, must have a public access-type, and there must not be a return type on the function. parameters may be included, but the same number of parameters must be included in the construction itself (explained later). a constructor is commonly used to set specific property values to use in the beginning. a normal constructor might look something like the following:

public function MyFirstClass(startTrace:Boolean, startCaps:Boolean):Void{
allCaps = startCaps;
canTrace = startTrace;
}


BBS Signature

Response to As: Oop Classes 2006-01-08 09:48:14


ENCAPSULATION
a common way of purging outside info of harmful data is encapsulation, and an example of this is the Sound class getVolume() and setVolume(). for instance, let us say that the person using this class writes in an code outside of the class MyFirstClassInstance.timesSpoken = 1000? this would clearly be bad, since timesSpoken serves as variable to store the number of times the sendMessage() method is called. so instead, we can write a public function to retrieve private data, like this:

public function getTimesSpkn():Number{
return timesSpoken;
}

public function traceLastMsg():Number{
trace("LAST MESSAGE: "+lastMessage);
}

another reason to encapsulate is to monitor or streamline input in a simple way. lets say that you wanted the user to have to run a special method such as setTimesSpkn() in order to have a way allow the user to set a lower number than is currently input. instead of just trusting the user to set the property properly, you can purge the unwanted input in a method, like this:

public function setTimesSpkn(num:Number):Void{
timesSpoken = Math.min(num, timesSpoken);
}

so now, the class we have looks like this:

class MyFirstClass{
public var allCaps:Boolean = false;
public var canTrace:Boolean = true;
private var lastMessage:String = new String("No Messages");
private var timesSpoken:Number = 0;

public function MyFirstClass(startTrace:Boolean, startCaps:Boolean):Void{
allCaps = startCaps;
canTrace = startTrace;
}

public function sendMessage(msg:String):Void{
if (!canTrace) return;
var curMessage:String = allCaps ? msg.toUpperCase() : msg;
trace(curMessage);
lastMessage = curMessage;
timesSpoken++;
}

public function getLastMsg():Number{
trace("LAST MESSAGE: "+lastMessage);
}

public function getTimesSpkn():Number{
return timesSpoken;
}

public function setTimesSpkn(num:Number):Void{
timesSpoken = Math.min(num, timesSpoken);
}
}

APPLYING CLASSES
now, to use this in a FLA (it is assumed you named the *.as file the same as the class name), all you have to do is datatype a variable to the class name. we actually created a constructor to set some starting values to specific variables, so let us fill it out as well.

var myMessenger:MyFirstClass = new MyFirstClass(true, false);

now, we can begin using the class however we would like. lets say that we want to trace a message that says "actionscript is fun". we could call the sendMessage() method:

myMessenger.sendMessage("actionscript is fun");
// output: actionscript is fun

but wait, what if we want to trace those same words in all caps:

myMessenger.allCaps = true;
myMessenger.sendMessage("actionscript is fun");
// output: ACTIONSCRIPT IS FUN

you could even store pieces of encapsulated information to a variable
howManyMessages = myMessenger.getTimesSpkn();
// howManyMessages = 2

EXTENDING A CLASS
one thing to learn at this point is "class extension". this is somewhat of a misnomer, since the terminology "class extension" would make you think that you are adding to the preexisting class. instead, the new class will automatically take on the properties and methods of the extended class.

class xSound extends Sound{
}

when you instantiate the xSound object, you will have access to the entire Sound library, including such methods as setVolume(), getPan(), start(), and stop(), and such properties as position and duration. a neat trick with extending preexisting classes is overwriting old methods. rarely useful, but possible.

the two most common uses for class extensions is to expand on a class by adding more methods that cater to your specific needs or add useful modifications, or to have a movieclip act as a tangible representation of an otherwise abstract object. remember that extended classes have access to any property in the extended class.

IMPLIMENTING CLASSES
for when a custom class needs to have the properties of multiple class, the class must "impliment" the other classes. for instance, if i wanted to create a custom Sound class, and i had a few other basic sound class modification classes i had written, i could impliment the other modification classes and still extend the original Sound class:

class xSound extends Sound impliments SoundModA, SoundModB{
}

this will model the xSound after the Sound, and will include the methods and properties of the SoundModA and the SoundModB classes. this is useful for combining already extended classes to create a versitile class extension.

alright, i hope that was informative. this was merely meant to be a companion guide to go with inglors AS OOP tutorial. feel free to post your class ideas and questions here to get a bit of help. the syntax is different in a few ways to normal AS, so be sure to learn the syntax, and remember: strict variable datatyping is your friend.

- authorblues


BBS Signature

Response to As: Oop Classes 2006-01-08 09:53:16


sweet, very informative and greatly explained.

Have some cool points. ^_^

I learnt something. :P

Response to As: Oop Classes 2006-01-08 10:00:46


Nice tutorial, heres an example of a simple class that adds a few mouse based variables. It's incredibly useful, I seriously use it all the time.

dynamic class MouseControl extends Mouse {
public function MouseControl() {
var mouseListObj:Object = new Object();
mouseListObj.onMouseDown = function() {
_global.mouseHeld = true;
};
mouseListObj.onMouseUp = function() {
_global.mouseHeld = false;
};
mouseListObj.onMouseMove = function() {
_global.mouseX = _root._xmouse;
_global.mouseY = _root._ymouse;
var curMousePos:Array = [mouseX-mousePosition[0], mouseY-mousePosition[1]];
var curMouseMath:Number = (curMousePos[0]*curMousePos[0])+(curMouseP
os[1]*curMousePos[1]);
_global.mouseSpeed = Math.sqrt(curMouseMath);
_global.mousePosition = [mouseX, mouseY];
};
Mouse.addListener(mouseListObj);
}
}


Sup, bitches :)

BBS Signature

Response to As: Oop Classes 2006-01-08 10:18:49


Response to As: Oop Classes 2006-01-08 10:26:44


At 1/8/06 10:18 AM, -yoshipros- wrote: TRY HERE

no... not try there. NG bbs gets much more views for authorblues's tutorial, and a lot more feedback, more people to learn basics of OOP.
Great job authorblues, I'm still trying to understand most of all of it but I'm gettin the hang of it. I'm gonna read through ti again hopefully get some more out of it. Nice job.

Response to As: Oop Classes 2006-01-08 10:33:29


havnt read it and probaly wont but it seems as though most of the information is there and will be great for AS beginners


- Matt, Rustyarcade.com

Response to As: Oop Classes 2006-01-08 10:35:41


At 1/8/06 10:18 AM, -yoshipros- wrote: TRY HERE

Please, stop plugging that crappy site in every thread you see.

And to authorblues, really good tutorial.

Response to As: Oop Classes 2006-01-08 10:36:52


At 1/8/06 10:18 AM, -yoshipros- wrote: TRY HERE

lol no.

Response to As: Oop Classes 2006-01-08 10:52:10


At 1/8/06 10:36 AM, TimHeasman wrote:
At 1/8/06 10:18 AM, -yoshipros- wrote: TRY HERE
lol no.

man that name really needs to be put back


- Matt, Rustyarcade.com

Response to As: Oop Classes 2006-01-08 10:54:29


I dnot undrstand therews errors lol

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 1: The class or interface 'TutorialBank' could not be loaded.
var ASMain:TutorialBank = new TutorialBank();

No, but seriously, a good tutorial, much needed. Maybe something on static and dynamic though? And packages?


BBS Signature

Response to As: Oop Classes 2006-01-08 10:54:29


good for the noobz but i pwn u all on as just so u no

join my teem!

Response to As: Oop Classes 2006-01-08 10:58:24


At 1/8/06 10:54 AM, 1234560 wrote: join my teem!

Shur al joyn ur teem! snds rly kl, bt i suk bt i wnna lern frm u! wtf is a class? i ate skool


Sup, bitches :)

BBS Signature

Response to As: Oop Classes 2006-01-08 11:03:45


At 1/8/06 10:58 AM, -liam- wrote:
At 1/8/06 10:54 AM, 1234560 wrote: join my teem!
Shur al joyn ur teem! snds rly kl, bt i suk bt i wnna lern frm u! wtf is a class? i ate skool

lol me 2. sonds kewl


BBS Signature

Response to As: Oop Classes 2006-03-21 18:01:53


dude i dont get this. this is my class file:

class zPoint {
public var x:Number;
public var y:Number;
public var z:Number;
public function zPoint(xSpot:Number, ySpot:Number, zSpot:Number) {
x = xSpot;
y = ySpot;
z = zSpot;
}
public function getDistance(p1:zPoint, p2:zPoint):Number {
return Math.sqrt(((p1.x - p2.x) * (p1.x - p2.x)) + ((p1.y - p2.y) * (p1.y - p2.y)) + ((p1.z - p2.z) * (p1.z - p2.z)));
}
}

its on zPoint.as. i have a fla in the same directory with this on the first frame:

import zPoint.as;
var myZPoint:zPoint = new zPoint(5,5,5);

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 2: The class or interface 'zPoint' could not be loaded.
var myZPoint:zPoint = new zPoint(5,5,5);

i tried import "zPoint.as"; but that didnt work, and it didnt work without the import thing either


This blog I made | This game sucks | I, twit

Just trying to get enough Twitter followers to quit Facebook forever

Response to As: Oop Classes 2006-03-21 18:12:09


Whats with this:

IMPLIMENTING CLASSES
for when a custom class needs to have the properties of multiple class, the class must

Are you talking about interfaces or inheritance ?! You are wrong with that part.... just look it up by pressing f1 when having highlighted the word "class"- And you should have done that before writing a tutorial about it (and yeah I know already that you hate me).

greets

Response to As: Oop Classes 2006-03-21 18:17:17


At 3/21/06 06:12 PM, LeechmasterB wrote: Are you talking about interfaces or inheritance ?! You are wrong with that part.... just look it up by pressing f1 when having highlighted the word "class"- And you should have done that before writing a tutorial about it (and yeah I know already that you hate me).

why do you continue bringing this to me. youre like a dog with a fucking bone.

By saying we implement an interface, we are agreeing to use all the methods declared in our interface. We dont have to use them all, we just leave the ones empty that we dont want to use.


BBS Signature

Response to As: Oop Classes 2006-03-21 18:23:10


My post contained nothing but facts and the least you could do is correct the mistake in a new added post right below this one for example. Or I feel the urge to do it myself... :)

And hey my post was totally correct and plain facts so why do you take it as an insult? You said I am the noob and told me to go learn as... and now all what I did was point out a big mistake in a tutorial, so do you wan't all noobs to learn something that is wrong?

greets

Response to As: Oop Classes 2006-03-21 18:25:27


why cant i use my class?


This blog I made | This game sucks | I, twit

Just trying to get enough Twitter followers to quit Facebook forever

Response to As: Oop Classes 2006-03-21 18:27:47


At 3/21/06 06:23 PM, LeechmasterB wrote: Blah blah blah

do you have to turn every single topic you post in a flame war? have you not noticed that everyone here hates you? all you do is try to show everyone how good you are but theres no point in doing it because you're just making yourself look like a moron. Grow up, i'm 14 and acting more mature than you.


========|| WWWWWWWW>[-[Blog] - [Audio] - [Userpage] - [Flash] - [Last.fm]-]<WWWWWWWW ||========

BBS Signature

Response to As: Oop Classes 2006-03-21 18:29:14


Just plain ignore that he says anything at all.
Pretend he doesn't exist.

Hey, it works for my cat.


Perpetually looking for time to return to the arts.

BBS Signature

Response to As: Oop Classes 2006-03-21 18:33:05


At 3/21/06 06:29 PM, Johnny_Krysys wrote: Just plain ignore that he says anything at all.
Pretend he doesn't exist.

... i see how it is.


This blog I made | This game sucks | I, twit

Just trying to get enough Twitter followers to quit Facebook forever

Response to As: Oop Classes 2006-03-21 18:33:13


Macromedia says:

[dynamic] class className [ extends superClass ] [ implements interfaceName[, interfaceName... ] ] {
// class definition here
}

Defines an interface. An interface is similar to a class, with the following important differences:

Interfaces contain only declarations of methods, not their implementation. That is, every class that implements an interface must provide an implementation for each method declared in the interface.
Only public members are allowed in an interface definition; instance and class members are not permitted.

Response to As: Oop Classes 2006-03-21 18:59:50


Hey and vengeance by the way... it was always the other guys starting the flaming and insulting. If you are not able to read through the threads and posts to find that out its too bad. Just its like one of you starts flaming and swearing and when I swear back because it starts pissing me off all of you come to help the other guy and flame too. And the final reward for getting flamed for no reason by you guys is telling me what i think and to leave "your" forum ect ... omg how do you know what i think, did you buy the bbs, who is everyone? So do not tell me that it was me starting the flame wars.. it wasn't me! Yes it was me who got pissed because of that but thats a normal reaction. And if you feel like continuing this conversation let it be in another thread.

greets

Response to As: Oop Classes 2006-03-22 01:39:19


At 3/21/06 06:23 PM, LeechmasterB wrote: You said I am the noob and told me to go learn as...

please quote me where i said something about you needing to learn AS
i believe you know it all quite well enough. theres no argument there.

and now all what I did was point out a big mistake in a tutorial, so do you wan't all noobs to learn something that is wrong?

my problem lies not in the fact that you correct my mistakes (not that i admit alterations when alterations find), its your smug sense of "i know more than everyone here". if you want to come in here, become a part of the group, prove what you know and how useful you can be, i welcome you, but to come onto these boards and pull up a perfectly fine tutorial with your smartass comments because you thought you found some huge fallacy is ridiculous.

by the way, this is what i refer to...

At 3/21/06 06:12 PM, LeechmasterB wrote: just look it up by pressing f1 when having highlighted the word "class"- And you should have done that before writing a tutorial about it

that is just unacceptable...


BBS Signature

Response to As: Oop Classes 2006-03-22 12:09:39


At 1/8/06 09:48 AM, authorblues wrote: class xSound extends Sound impliments SoundModA, SoundModB{
}

this will model the xSound after the Sound, and will include the methods and properties of the SoundModA and the SoundModB classes. this is useful for combining already extended classes to create a versitile class extension.

alright. i rechecked my sources, and based on what i had read, i wrote the tutorial right. i did however look further in-depth on this, and it turns out that implimentation actually inherits nothing, quite the opposite in fact. implimented class create a blueprint that you must actually fill in yourself.

if the implimented class contains a function such as doThis(), you must redefine doThis() in the new class, with either a new set of functions, or just leave it empty.

TO LEECHMASTER

having me correct my information is one thing. i appreciate that. do not, however, act as if i (i want to say we, but im speaking for myself here) started this war with you. you are a smartass and a know-it-all, and to respond in the way you did is STILL entirely unacceptable.


BBS Signature

Response to As: Oop Classes 2006-03-22 12:21:32


Selfless promotion

Also, I just noticed - where you put "accessType", that's actually the namespace =P It doesn't matter though, just nitpicking [not literally, duh].


Sup, bitches :)

BBS Signature

Response to As: Oop Classes 2006-03-22 12:26:16


At 3/22/06 12:21 PM, -liam- wrote: Selfless promotion

Also, I just noticed - where you put "accessType", that's actually the namespace =P It doesn't matter though, just nitpicking [not literally, duh].

there are 64 people on your sig and im not one of them :(

Response to As: Oop Classes 2006-03-22 13:08:47


At 3/22/06 12:26 PM, -reelbigcheese- wrote: there are 64 people on your sig and im not one of them :(

Ha ha, I made that yesterday because someone made a topic in the general forum (I went there for the first time in ages) where you tell him your name then he'll make an animated sig with the names on - it came out shite so I made that one. I'll make a Flash forum one soon ^_^


Sup, bitches :)

BBS Signature

Response to As: Oop Classes 2006-03-22 13:14:57


At 3/22/06 01:08 PM, -liam- wrote: Ha ha, I made that yesterday because someone made a topic in the general forum (I went there for the first time in ages) where you tell him your name then he'll make an animated sig with the names on - it came out shite so I made that one. I'll make a Flash forum one soon ^_^

yey cool, you should do it now make a new topic :)