Actionscript For Java Developers: James Ward at - Jamesward
Actionscript For Java Developers: James Ward at - Jamesward
ActionScript for
J ava Developers
J ames Ward
www.jamesward.com
@_J amesWard
Flex Intro
Flex is a set of libraries for developing Flash applications
Flex programs are written in ActionScript3 and MXML
MXML is a declarative markup language
preprocesses into AS3
2
<mx:Object id="o" foo="bar"/> var o:Object = new Object();
o.foo = "bar";
MXMLC
From Flex code to Flash App
MXML
code
AS3
code
Generated
AS3 Code
Flex
SDK
Classes
Flex Compiler
SWF File
ActionScript3 Intro
J ava and AS3 are remarkably similar in many ways
Both have
classes
interfaces
object-oriented style of programming
types
But there are some differences
4
same syntax?
5
package foo;
import somepackage.*;
public class Foo
extends FooParent
implements IFoo
{
private String blah = "blah";
/**
* bar performs important string-
* setting functionality
*
* @param b the String to be set
*/
public boolean bar(String b) {
blah = b;
return true;
}
}
package foo {
import somepackage.*;
public class Foo
extends FooParent
implements IFoo
{
private var blah:String = "blah";
/**
* bar performs important string-
* setting functionality
*
* @param b the String to be set
*/
public function bar(String b):Boolean {
blah = b;
return true;
}
}
}
same syntax?
6
package foo;
import somepackage.*;
public class Foo
extends FooParent
implements IFoo
{
private String blah = "blah";
/**
* bar performs important string-
* setting functionality
*
* @param b the String to be set
*/
public boolean bar(String b) {
blah = b;
return true;
}
}
package foo {
import somepackage.*;
public class Foo
extends FooParent
implements IFoo
{
private var blah:String = "blah";
/**
* bar performs important string-
* setting functionality
*
* @param b the String to be set
*/
public function bar(String b):Boolean {
blah = b;
return true;
}
}
}
Agenda
Syntax
Properties
Dynamic Behavior
Classes
Functions
Events
Primitives & Data Structures
Puzzlers
7
The Wages
of
Syntax
Type Syntax
J ava does this
9
public int blah;
public Object foo = new Object();
var Syntax:Type
J ava does this
AS3 does it this way
10
public int blah;
public Object foo = new Object();
public var blah:int;
public var foo:Object = new Object();
Undefined != null
J ava has no 'undefined' concept
AS3 has undefined, null, Nan
11
Object foo;
Number num;
System.out.println(foo);
// outputs 'null'
System.out.println(num);
// outputs 'null'
var foo;
var bar:Object;
var num:Number;
trace(foo);
// outputs 'undefined'
trace(bar);
// outputs 'null'
trace(num);
// outputs 'NaN'
Package Declarations
J ava declares packages up top
AS3 puts classes inside package block
12
package foo;
class FooThing {
}
package foo {
class FooThing {
}
}
Scope
In J ava, scope is defined by the enclosing block:
In AS3, scope is function-wide:
13
// using i for both is fine completely separate scopes
public void foo() {
for (int i = 0; i < 10; ++i) {}
for (int i = 0; i < 5; ++i) {}
}
// causes a compiler warning
public function foo():void {
for (var i:int = 0; i < 10; ++i) {}
for (var i:int = 0; i < 5; ++i) {}
}
// better:
public function foo():void {
var i:int;
for (i = 0; i < 10; ++i) {}
for (i = 0; i < 5; ++i) {}
}
Metadata
J ava annotations
AS3 metadata
14
@Foo
public class Bar {
@Monkey
String banana;
}
[Foo]
public class Bar {
[Monkey]
var banana:String;
}
Semicolons
J ava;
Requires;
Semicolons;
AS3
Does
Not
Unless; You; Do; Multiple; Operations; On; A; Single; Line;
(but readable code should use them)
15
final vs. const
J ava uses 'final' for constants
AS3 uses 'const'
16
public final int FOO = 5;
public const FOO:int = 5;
Casting Call
J ava
AS3
and
17
float foo = 5;
int fooInt = (int)foo;
var foo:Number = 5;
var fooInt:int = int(foo);
var foo:Number = 5;
var fooInt:int = foo as int;
Exceptional Handling
J ava throws up
AS3 throws without declaration
public void foo() throws MyException
{
try {
// really awesome code
} catch (Exception e) {
throw new MyException("AAAUUUGGGHHHH!");
}
}
public function foo():void
{
try {
// really awesome code
} catch (var e:Error) {
throw new Error("AAAUUUGGGHHHH!");
}
}
Generics
J ava has generics and typed collections
AS3 does not
but it does have a typed Vector class
19
List<FooType> list = new ArrayList<FooType>();
list.add(new FooType());
FooType foo = list.get(0);
var vec:Vector.<FooType> = new Vector.<FooType>();
vec[0] = new FooType();
var foo:FooType = vec[0];
XML Handling
J ava processes XML through libraries (many of them)
J AXP, J AXB, SAX, Xerces, J DOM,
AS3 has 'e4x'
e4x has queries, XML manipulation,
var myXML:XML = <Grob>gable</Grob>;
trace(myXML.Grob);
// outputs 'gable'
Proper
Tease
Properties: J ava
J ava has J avaBeans conventions for getters/setters
22
public class JavaProps {
public int blah;
private int foo;
public void setFoo(int value) {
foo = value;
}
public int getFoo() {
return foo;
}
}
JavaProps props = new JavaProps();
props.blah = 5;
props.setFoo(5);
Properties: AS3
AS3 has properties as first-class citizens via get/set
23
public class AS3Props {
public var blah:int;
private var _foo:int;
public function set foo(value:int):void {
_foo = value;
}
public function get foo():int {
return _foo;
}
}
AS3Props props = new AS3Props();
props.blah = 5;
props.foo = 5;
Properties: AS3
public class AS3Props {
public var foo:int;
}
public class AS3Props {
private var _foo:int;
public function set foo(value:int):void {
_foo = value;
}
public function get foo():int {
return _foo;
}
}
is equivalent to
Properties: AS3
Variable -> set/get change can be made without affecting
public API
In J ava, need to define set/get functions up front
Can't have users rewrite code later on change of foo to
setFoo/getFoo
In AS3, can replace variable with set/get functions any
time
Note: cannot override instance variables in subclasses
set/get is a good convention to follow in general, when
subclassing is expected
25
Property Access
J ava accesses named fields checked at compile time
AS3 provides the same syntax
But Object or untyped is more flexible
var foo:FooType = new FooType();
foo.x = 5;
// compiler error if x not in FooType
foo["x"] = 5;
// runtime error
FooType foo = new FooType();
foo.x = 5;
// compiler error if x not in FooType
var foo:Object = new Object();
var bar:* = new Object();
foo.x = 5;
bar.x = 5;
// no compiler errors
Property Access
AS3 allows access to properties via Strings
Useful for access of arbitrary fields known only at runtime
var foo:Object = new Object();
foo["x"] = 5;
var arg:String = "x";
foo[arg] = 5;
Dynamic Behavior: maps
In J ava, hashmapping is handled by libraries
In AS3, every Object is a String map
but Dictionary is used for Object mapping
28
HashMap map = new HashMap();
map.put("foo", 5);
Object blah = new Object();
map.put(blah, 14.0);
var map:Object = new Object();
map["foo"] = 5;
var map:Dictionary = new Dictionary();
var blah:Object = new Object();
map[blah] = 14.0;
Dynamism: maps
In AS3, arbitrary classes can also perform mapping, if
declared dynamic:
29
public dynamic class MyClass {
// [interesting behavior deleted]
}
var map:MyClass = new MyClass();
map.foo = 5;
Dynamic Arrays
In J ava, Arrays are declared with a set size
In AS3, Arrays are dynamic
30
Array myArray = new Array(1);
myArray[0] = new Object();
myArray[1] = new Object();
// throws really long ArrayIndexOutOfBoundsException
var myArray:Array = [];
myArray[0] = new Object();
myArray[1] = new Object();
// no problem
Untyped properties
J ava doesn't do untyped properties
AS3 allows untyped, will be void-typed
31
Object foo;
bar;
// Compiler pukes on bar declaration
var foo:Object;
var bar;
var blah:*;
// bar and blah will both be void-typed
Object Creation
J ava populates variables through construction, or through
manual sets after construction
AS3 allows J SON-like setting of properties on Objects
32
public class FooObject {
int blah;
}
FooObject foo = new FooObject();
foo.blah = 5;
var foo:Object = {blah:5};
A
Class
Act
Constructor Permissions
J ava allows permissions on constructors
AS3 constructors must always be public
34
public class FooObject {
private FooObject() {}
}
FooObject foo = new FooObject();
// Compiler error if in another class
public class FooObject {
private function FooObject() {}
}
// Compiler error
Properties and Interfaces
J ava allows properties and constants on interfaces
(by the way, these are implicitly final and static)
AS3 does not
public interface IFoo {
public int blah = 5;
public final int VAL = 7;
}
Abstract Classes
J ava allows abstract classes
AS3 does not
36
public abstract class FooObject {
public abstract void foo();
}
Namespaces
J ava has permissions
public, private, protected, package-private
But not 'namespaces'
AS3 has namespaces
public, private, protected, internal
37
Namespaces
package example {
public namespace myNamespace = "http://foo.com/blah";
}
package example.a {
import example.myNamespace;
public class Foo {
myNamespace static var bar:Object;
}
}
package example.b {
import example.myNamespace;
use namespace myNamespace;
public class Blah {
public function Blah() {
trace(Foo.bar);
}
}
}
Form
vs.
Function
Functions as Objects
J ava
methods are members of classes
AS3
functions are Objects
in fact, function extends Object
40
Functions and Packages
J ava has functions only at the class level
AS3 has functions at package and class level
(single file may have only one public class or function)
package foo;
public class MyClass {
public void blah() {}
}
package foo {
public function bar():void {}
}
package foo {
public class MyClass {
public function blah():void {}
}
}
Function Overloading
J ava can have multiple overloads of same function
AS3 can have only one
but: default parameter values provide workaround
public void blah() {}
public void blah(String bar) {}
public function blah():void {}
public function blah(bar:String):void {}
// compiler error
public function blah(bar:String = ""):void {}
blah();
blah("Grob");
Default values
J ava does not allow parameter values in functions
AS3 does, with some options
public function blah(foo:int, bar:String = ""):void {}
blah(5);
blah(5, "Groob");
... args
AS3 supports variable number of args
public function blah(... args):void {}
blah(5);
blah(5, "Groob");
public function blah(first:int, ... rest):void {}
blah(5);
blah(5, "Groob", "blah");
Anonymous Functions
J ava has methods only in context of classes
AS3 can have anonymous functions, declared inline
var f:Function = function():void {};
f();
Function Passing
J ava method accessed is only through objects
not method-passing (possible with Reflection)
AS3 functions are objects and can be passed around
willy-nilly
public class Foo {
public static function blah():void {}
}
bar.blahRef = Foo.blah;
bar.blahRef();
public function groob(func:Function):void {
func();
}
groob(Foo.blah);
Overrides
J ava overriding is automatic
same method signature in subclass overrides
superclass method
AS3 requires 'override' keyword
public class Foo { // extends Object
override public function toString():String {}
}
In
any
Event
Events: J ava
J ava: Manually set up event listening and dispatching
create addListener()/removeListener() methods
manage listener list
when appropriate, iterate through listeners and send out events
49
public void addEventListener(IFoo listener) {
// manage listeners
}
public void removeEventListener(IFoo listener) {
// manage listeners
}
public void someMethod() {
// dispatch event to listener list
}
Events: AS3
AS3: Most visual items are event dispatchers already
Your class needs to expose the event type it dispatches
Done via metadata
Listeners just add themselves via addEventListener()
Flash automatically manages listeners, dispatches events
50
[Event(name="someEvent", type="SomeEventType")]
public void someMethod() {
dispatchEvent("someEvent");
}
Primitives &
Data Structures
Numbers
AS3 has 3 number types:
uint - 32 bit unsigned integer
int - 32 bit signed integer
Number - IEEE-754 double-precision floating point
NO long integer / 64-bit integer!!
Puzzlers
This Function
What is the output for the following code:
var f:Function = function(that:Object):void {
trace(this === that);
}
f(this);
A)
true
B)
false
C) Runtime error
D) Compile error
This Function
What is the output for the following code:
var f:Function = function(that:Object):void {
trace(this === that);
}
f(this);
A)
true
B)
false
C) Runtime error
D) Compile error
This Function
Anonymous functions aren't in the same scope as a function on a
class
You can use Function.call() or Function.apply() to overwrite the
"this" within a function call.
Array Casting
What is the output for the following code:
var a:Array = ['a', 'b', 'c'];
trace(Array(a)[0]);
A)
a
B)
a,b,c
C) Runtime error
D) Compile error
Array Casting
What is the output for the following code:
var a:Array = ['a', 'b', 'c'];
trace(Array(a)[0]);
A)
a
B)
a,b,c
C) Runtime error
D) Compile error
Array Casting
Casting an object to an Array (when not using the "as"
operator) a new Array is created with the first element being
the Array that was "casted".