Follow Flex After Dark on Twitter

ActionScript 3 vs. Java

ActionScript and Java are both powerful, object-oriented languages with many similarities.

Both Java and ActionScript:

  • Are object-oriented
  • Use single inheritance
  • Have a base Object class (which is automatically sub-classed)
  • Use strongly typed variables
  • Have Packages, Classes, and Interfaces
  • Support public, protected, and private methods and variables
  • Support static functions and variables
  • Support try/catch/finally exception handling

There are also many differences between ActionScript and Java.

Important differences between Java and ActionScript:

  • ActionScript has get/set functions
  • ActionScript supports dynamic classes
  • ActionScript supports closure functions
  • ActionScript supports optional function arguments, but does not support overloading
  • ActionScript does not allow private classes or constructors

Classes and Interfaces

Both Java and ActionScript require classes/interfaces to be declared in a package and the explicit import of used classes/interfaces that are not in the same package. (Both also allow the package name to be ommitted, representing the default package.)

Class Definition

Java class definition:

package packageName;

import another.packageName.*;

public class ClassName extends SuperClassName implements InterfaceName
{
   public ClassName()
   {
      // constructor
   }
}

ActionScript class definition:

package packageName
{
   import another.packageName.*;
   
   public class ClassName extends SuperClassName implements InterfaceName
   {
      public ClassName()
      {
         // constructor
      }
   }
}

ActionScript also supports dynamic classes.

Interface Definition

Java interface definition:

package packageName;

public class InterfaceName extends AnotherInterface
{
   // public is optional (and extraneous)
   public void methodName();
}

ActionScript interface definition:

package packageName
{
   public interface InterfaceName extends AnotherInterface
   {
      // public not necessary (and not allowed)
      function methodName():void;
   }
}

Unlike Java, ActionScript Interfaces do not allow property definitions.

Variables

Both Java and ActionScript use strongly-typed variables.

Java variable definitions:

   Object object = new Object();
   int count = 1;
   String name = "Donnie Brasco";
   String[] names = { "Alice", "Bob", "Carl" };

ActionScript variable definitions:

   var object:Object = new Object();
   var count:int = 1;
   var name:String = "Donnie Brasco";
   var names:Array = { "Alice", "Bob", "Carl" }; // ActionScript arrays are untyped

ActionScript does support typeless variables, but it is generally not encouraged. Learn more in the ActionScript language document...

Methods/Functions

Java method and ActionScript function declarations share the same elements, just in different orders.

Java method definition:

   public String doSomething( Object arg )
   {
      return "something";
   }

ActionScript function definition:

   public function doSomething( arg:Object ):String
   {
      return "something";
   }

public function functionName( argName:ArgType ):ReturnType

ActionScript also allows optional function arguments.

ActionScript function definition with optional function argument:

   public function anotherFunction( arg:Object, opt:String=null ):void
   {
      // do something
   }

In the above example, the opt argument is optional because it has a default value assigned in the function signature. Optional arguments must be declared after those that are required.

Read more about ActionScript Functions...

Casting and Runtime Type Checking

In strongly-typed languages, such as Java and ActionScript, it is sometimes necessary to cast the reference of one typed variable to another. For example, if you have a Person object referenced just as Object (every object's super-type), but you need to get it cast as its more specific type.

Java runtime type checking and casting:

   // cast Object to Person
   if( object instanceof Person )
   {
      Person person = (Person) object;
   }

ActionScript runtime type checking and casting:

   // cast Object to Person
   if( object is Person )
   {
      // note the lack of the new keyword
      var person:Person = Person( object );
   }

For runtime type checking Java uses the instanceof operator, ActionScript uses is.

ActionScript also offers another method, similar to casting, using the as operator. The ActionScript as operator will cast the object and assign it the variable, but only if object is of the proper type (otherwise it assigns null).

ActionScript usage of the as operator:

   // use "as" to safely assign object as a Person or null
   var person:Person = object as Person;

Looping

Looping in Java and ActionScript have similar notations.

Java "for" loops:

   // loop over an array
   for( int i = 0; i < array.length; i++ )
   {
      // use array[i]
   }
   
   // loop over a collection
   for( Object item : collection )
   {
      // use item
   }

ActionScript "for" and "for each" loops:

   // loop over an array
   for( var i:int = 0; i < array.length; i++ )
   {
      // use array[i]
   }
   
   // loop over a collection
   var item:Object;
   for each( item in collection )
   {
      // use item
   }

Exceptions

Both Java and ActionScript throw exceptions and support the try/catch/finally structure for handling them.

Java exception handling using try/catch/finally:

   // method declared to throw an exception
   public void doSomething() throws Exception
   {
      try
      {
         // try something
      }
      catch( Exception ex )
      {
         // handle exception by rethrowing
         throw ex;
      }
      finally
      {
         // reached whether or not there's an exception
      }
   }

ActionScript exception handling using try/catch/finally:

   // functions do not declare that they throw
   public function doSomething():void
   {
      try
      {
         // try something
      }
      catch( error:Error )
      {
         // handle error by rethrowing
         throw error;
      }
      finally
      {
         // reached whether or not there's an exception
      }
   }

Best Practices

Accessor Functions (Get/Set)

Java and ActionScript handle the encapsulation of getting and setting properties quite differently.

In Java its standard practice to privatize all instance variables and expose getter and setter functions where appropriate. The goal is to encapsulate how properties are stored and allow it to change without changing the class's contract.

Java example of getter/setter functions:

public class Person
{
   private String name = null;
   
   public String getName()
   {
      return this.name;
   }
   
   public void setName( String name )
   {
      this.name = name;
   }
}

The above code could be used as followed:

   person.setName( "John" );
   String example = person.getName(); // returns "John"

In Java, most getter/setter methods are just boilerplate, often generated automatically for each property. In other words, they are often just a necessary evil.

ActionScript, however, has support for special get and set functions that can encapsulate property access behind function calls, but without changing the property access syntax. Before further explanation, let's see an example.

public class Person
{
   public var name:String;
}

The above code could be used as followed:

   person.name = "John";
   var example:String = person.name; // returns "John"

But what if we wanted to change the mechanics of how the name property is stored? We could modify the above example to use get/set functions.

ActionScript example of get/set function usage rather than a public property:

public class Person
{
   private var _name:String;
   
   public function get name():String
   {
      return _name;
   }
   
   public function set name( value:String ):void
   {
      _name = value;
   }
}

Note the extra "get" and "set" keywords in the function declarations. This tells ActionScript that the functions are for property access. While the code looks quite different than just using a public property, the usage is exactly the same.

The above code could still be used as followed:

   person.name = "John";
   var example:String = person.name; // returns "John"

The key point of get and set functions is that you can start with public properties and later move to get/set functions, if necessary, without changing how the class is used.

Learn more about Get/Set Functions in ActionScript...

Code Examples

Creating a Singleton

Java example of the Singleton pattern:

package examples;

public class Singleton
{
   private static final Singleton _instance = new Singleton();
   
   private Singleton()
   {}
   
   public Singleton getInstance()
   {
      return _instance;
   }
}

ActionScript example of the Singleton pattern:

package examples
{
   public class Singleton
   {
      static private const _instance:Singleton = new Singleton();
      
      // private constructors not supported
      public Singleton()
      {
         if( _instance )
         {
            throw new Error( "Singleton instance already exists." );
         }
      }
      
      static public function get instance():Singleton
      {
         return _instance;
      }
   }
}

Related Links:

Related Docs
  • Object-Oriented ActionScript ActionScript is a full-featured Object-Oriented language with support for classes, interfaces, encapsulation, polymorphism, and inheritance.
  • ActionScript Language Introduction to the ActionScript 3.0 programming language.
Recent Docs
  • ActionScript vs Java ActionScript has many similarities to the Java programming language.
  • ActionScript XML ActionScript has powerful XML support via E4X.
  • ActionScript Get/Set Functions ActionScript Get/Set Functions are special function handlers for property accessors.
  • Flex Binding Flex Data Binding enables objects and their values to be bound together so that when a source changes a target automatically gets updated.
  • Flex Modules Flex Modules are compiled to dynamically-loadable SWF files that can be loaded and unloaded at run-time.
Random Docs