Posts tagged ‘OOP Tutorial’
Beginners OOP ActionScript Tutorial – part 3
For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Beginners Flash CS3 Video Tutorial.
Instance Variables
Instance Variables are variables that are contained in each ‘instance’ of the Class; so every instance of the TextHandler Class will have it’s own TextFormat variable. Instance Variables should be initialised (given an initial value) in the constructor function, which is called whenever an Object of the Class is created. It is important, however, to refer to the instance variables outside the constructor, as in the above example, so that they are ‘visible’ to the entire Class.
Constructor Function
When you use the keyword ‘new’ to create an Object of a Class, what actually happens is that the ActionScript code within the constructor function for the Class is executed, returning an Object of the Class. The constructor function does not have to have the return type specified, as it is identified by having the same name as the Class itself.
To illustrate, imagine you wanted to create several of the TextHandler Objects, each with different formatting (i.e. different colour, font etc); you could alter the Class declaration so that the constructor function takes parameters indicating e.g. the colour, and these properties of the TextFormat object could be set within the constructor code. This way your main application code could create several different Objects of the TextHandler Class, each handling the textfields that you want to format in the same way (make the changes to your Class declaration and Flash document code):
//class code constructor
public function TextHandler(col:Number)
{
tf=new TextFormat();
tf.color=col;
}
//main code creating object
var myHandler:TextHandler = new TextHandler(0xFF0000);
To test this, place another dynamic textfield on your stage and name it other_txt, again with arbitrary text in it. Now add the following to your Flash document code:
var otherHandler:TextHandler = new TextHandler(0x0000FF); otherHandler.formatText(other_txt); //When you test the movie, other_txt should appear blue.
This trivial example may appear odd at first, but once you have gotten into the habit of thinking in terms of Objects, you’ll soon see how the techniques can save you a lot of stress. Experiment within your applications by creating Classes and Objects, with the following additional guidance:
- Functions can have as many parameters (of any datatypes) as you need, but can only have one return type; you must declare this when you devise the method (as in the stripChars function above where the return type is specified as String).
- The functions within a Class that are declared with the keyword ‘public’ are those that can be called on any Object of that type, wherever it has been created, as with the formatText method above.
- Additionally, Classes may feature private functions that are for use within the Class only; these are referred to as ‘helper’ functions and are used in much the same way as the stripChars function was in our original example. You will use such functions within your Classes where processing is repetitive or where the code contained within a function becomes overly long or complicated.
Class Overview
Look again at the (amended) version of your TextHandler Class declaration. In terms of the interface, the Class contains a constructor function (which takes one parameter of the type Number, representing the colour) and a single function for formatting text, which takes one parameter of the type textfield, and returns nothing.
Try adding more functions to the Class – e.g. add the stripChars function, using the keyword ‘public’ in front of it, then try calling it from your movie, passing it a String as in the original example.
In theory, the TextHandler Class could have been created by someone else and you could still use it as long as you know: what the Class is for, what the functions are called (and what their purpose is), what parameters they take, and what data they return, if any. If you think about it, this is all you know about the built-in Classes that you use regularly.
The ‘interface’ can also be made more explanatory through the use of documentation and comments, as is the case with the built-in Classes. You can see an example of this with the official Adobe documentation for the TextFormat Class in ActionScript 3.0 here: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/text/TextFormat.html
- this gives you limited insight into the TextFormat Class declaration.
As with the stripChars helper function example above, if at any stage during your development process, you decide to change any of the implementation details within your Classes’ functions, you should be able to do so without upsetting any other code, as long as your interface remains the same. e.g. If you decided to change the for loop in the stripChars function to a while loop (for whatever reason) it wouldn’t affect the rest of the code, as long as it performs the same function.
Summary
The Object Oriented design method is a good way to achieve well-organised applications, but the success of the technique does depend strongly on Classes being defined in a clear manner. If you’re struggling at all to grasp the technical notions, have a try at using Classes anyway; as long as you stick to the principles outlined above, you should be able to define and create useful Objects.
It can be challenging to understand these notions when you’re starting out as a programmer and have built only relatively small applications. However, even where you are developing applications single-handed, Object Oriented design can make for efficient programs that are easily manageable.
If you’re interested in exploring Object Oriented development further, advanced areas to study include: Packages; Inheritance; Polymorphism; Interfaces; Abstract Classes.
Beginners ActionScript OOP Tutorial Part 2
For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Flash CS3 Training CD.
Beginners OOPÂ with ActionScript – part 2
Using Objects
To use an Object Oriented approach, you need to learn to characterise your applications in terms of ‘Objects’, interacting with one another to deliver your program. With larger applications, this will be a ‘high-level’ analysis of the various program requirements, and is carried out before any programming takes place. For example, with languages for which Object Oriented development is often used, such as Java and C++, applications are normally built by a team of people. In these circumstances, each member/ section of a team will be responsible for developing specific parts of the application. When it comes to building the application as a whole out of these component parts, it is vital that the parts have what’s called a ‘well-defined interface’. This means that the different components can work together, without having to know each others details.
For example, when you use the Classes built-in to ActionScript as in the above example, you can create Objects of the TextFormat class and use its various methods easily, without having to understand how these methods are actually implemented in the underlying code. Similarly, when you create your own Classes, you will decide on the data and functions that any Objects of the Class will have, but the details of how these functions are carried out will remain relevant only within the Class itself. So in order for this approach to be successful, you need to ensure that your Classes have meaningful, clearly defined behaviour.
To demonstrate, let’s create a simple Flash application with a Class declaration. In this example, you are creating a movie that carries out various operations on text/ textfields (among other things). Given that this is a regular feature of your program, you decide to create an Object that will be responsible for all tasks relating to text; meaning that it will contain all text/textfield-related code. Your Class declaration might be something like this (further explanation follows):
class TextHandler
{
//class instance variable
var tf:TextFormat;
//constructor function - initialises any instance variables
public function TextHandler()
{
tf=new TextFormat();
tf.color=0xFF0000;
}
//function to format text with the TextFormat
public function formatText(txtField:TextField):Void
{
txtField.setTextFormat(this.tf);
}
//the class would also have other functions relating
//to text processing
}
This code should be saved in a file named ‘TextHandler.as’ identifying it as an ActionScript class file. Once you’ve defined a Class declaration like this, you can then create ‘instances’ of the Class in your main code; these are the ‘Objects’. You can then use the Objects to carry out the functionality contained in the Class declaration. To do this, create a new Flash document and save it in the same directory as your TextHandler.as file, then create a dynamic textfield on the stage, giving it the instance name my_txt, and put some arbitrary text in it:
//in your main code - Flash file in the same directory //as the class import TextHandler; //create an object of the class TextHandler var myHandler:TextHandler = new TextHandler(); //call a function on it - the movie contains my_txt textfield myHandler.formatText(my_txt);
When you test your movie, the text should appear red.
Beginners ActionScript Object Oriented Programming part1
For users who prefer to learn Flash visually we have a range of Adobe Flash CS3 video tutorials, this method of training greatly enhances learning and allows beginners to master even the most complex aspects of Adobe Flash with ease.
View the Adobe Flash CS3 Tutorial.
Object Oriented Programming with ActionScript – part 1
As your Flash applications grow more complex, relying on substantial amounts of ActionScript code, efficiency will become more of an issue. Applications that use well-organised code are more reliable, and lend themselves better to future extension. One approach to developing such systems is Object Oriented design, which we will explore in this tutorial. Even if you’re new to the concept of Object Oriented design, you may find that you have already adopted some of the techniques on which it is based.
The Concept of OOP with ActionScript
You will likely already have used Objects in your ActionScript code whether you’re aware of it or not. For example, your code may have used the TextFormat class:
var tf:TextFormat = new TextFormat();
In this example, we create a new Object of the Class TextFormat. This means that the Object has the properties and behaviour that are defined in the TextFormat Class declaration. This Class is part of ActionScript itself, and you can therefore create and use TextFormat Objects just by inserting the single line above. With Object Oriented design, you will be designing your own Objects, by creating Class declarations for them in ActionScript, then importing them into your Flash for use there.
The concept of Object should be familiar to you if you have used Library items and Symbols in Flash. When you create a MovieClip, for example, and define what happens within it, the MovieClip symbol in your library is like a blueprint or prototype for that kind of Symbol. When you then use instances of the MovieClip Symbol within your Flash movie itself, each of these instances has the properties and behaviour that you defined when you created the MovieClip originally. This process is analogous to what you’ll do with your ActionScript Classes. The Class declaration is where you define the properties (in ActionScript) that any instances of the Class will have when you create them, as with the TextFormat object above.
Well-organised code
The reason for adopting any design methodology is to produce applications that are reliable, efficient and easy to perform future amendments or extensions upon. This is similarly the case with Object Oriented development. To begin, we will look at some of the simple efficiency measures that you can take during your regular programming routine, and demonstrate how these form the basis for the Object Oriented approach.
There are many techniques to achieving well-organised code when creating Flash applications. The simple act of including plenty of comments and whitespace in your code makes for a component that is easier to debug and extend. Similarly, organising your code into sensible chunks of related processing is helpful. When doing this, creating what are referred to as ‘helper’ functions (something that you may have already done), illustrates the basic principle behind Object Oriented design.
Let’s look at a simple example. When you are writing ActionScript code, you will often find that you are carrying out similar processes repetitively. When this is the case, you should consider creating functions to carry out those processes, effectively allowing you to cut down on the amount of code you need to achieve the same functionality. Imagine you have a Flash movie that contains several text Strings whose content varies, maybe the text is being imported from some external file which has unpredictable content. You have decided that you don’t want to display any content that isn’t alphanumeric, i.e. you only want letters and numbers. For this reason you will have to perform text processing on each of the Strings before you display them. Your code might look like this (feel free to paste this into a Flash document to try it out – don’t worry too much about the String processing code if it’s unfamiliar to you, the details are unimportant, but pay attention to the overall structure of the code):
//strings - nonsense var first_str:String="kdfHGKj kkv e$ deagf% /.;fghlkjsf'h'"; var second_str:String="bcn'l;gH;'(fghsf "; var third_str:String="bcnf..,\\gj[] *dFG"; //strip out non alphanueric from first var firstStripped_str:String=""; for(var i:Number=0; i="0" && ch<="9") || (ch>="a" && ch<="z")) firstStripped_str+=first_str.charAt(i); } trace(firstStripped_str); //strip out from second var secondStripped_str:String=""; for(var j:Number=0; j="0" && ch<="9") || (ch>="a" && ch<="z")) secondStripped_str+=second_str.charAt(j); } trace(secondStripped_str); //strip third var thirdStripped_str:String=""; for(var k:Number=0; k="0" && ch<="9") || (ch>="a" && ch<="z")) thirdStripped_str+=third_str.charAt(k); } trace(thirdStripped_str);
This can be easily improved by making a ‘parameterised’ function, meaning a function that will carry out the same processing but which takes the Strings as parameter, making it adapt to each different circumstance:
//strings - nonsense
var first_str:String="kdfHGKj kkv e$ deagf% /.;fghlkjsf'h'";
var second_str:String="bcn'l;gH;'(fghsf ";
var third_str:String="bcnf..,\\gj[] *dFG";
function stripChars(my_str:String):String
{
var stripped_str:String="";
for(var c:Number=0; c="0" && ch<="9") || (ch>="a" && ch<="z"))
stripped_str+=my_str.charAt(c);
}
return stripped_str;
}
trace(stripChars(first_str));
trace(stripChars(second_str));
trace(stripChars(third_str));
Notice how much more concise the code is – test the movie to check that both versions of the code have the same effect. What you have done is to give the function ‘responsibility’ for the text processing. One of the advantages to doing this is that, if you decide to change the process in any way, you only have to do it in one place (within the function) – this is a single ‘point of change’. Eventually, when you have gotten into the habit of thinking this way when writing your code, you will start to anticipate the practice, rather than carrying it out retrospectively, and will save yourself a lot of time and effort in doing so.
While the above technique does make the code more efficient, it is still ‘procedural’ rather than Object Oriented in structure. Procedural programs are basically a series of instructions being executed in turn. When the movie is run, the code listed on the main timeline is executed in a linear fashion, i.e. each line is processed one after the other until the machine is instructed otherwise. To adopt Object Oriented design, we need to extend the notion of creating ‘helper’ functions, and to develop ‘helper’ Objects to carry out the processing within a movie. In the same way that we allocated the text-processing responsibility to a function, we can assign responsibility for the individual parts of an application to Objects – we can ‘delegate’.