Action Script For Java Developers-1

  • December 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Action Script For Java Developers-1 as PDF for free.

More details

  • Words: 2,180
  • Pages: 9
ActionScript for Java developers, Part 1

Figure 1. A similar class written in Java and ActionScript 3. Differences are shown in bold. (Click to enlarge.) So while I'm not a language expert (I'll keep emphasizing that, to make sure that nobody sends me questions about lambda expressions or BNF grammars or anything else I can't answer), I thought that it would be useful to take a step back from both languages and compare them from this programmer's point of view. I'll compare various aspects of the languages to see what ActionScript 3 looks like to a Java developer. In so doing, I hope to help you avoid some of the pitfalls and misconceptions I encountered in my own migration to the Flex SDK.

On the delicate art of comparison The goal of this article is not to depict one language as better than the other. I think that all languages have their place (I could throw in an unkind jibe here about some older or untrendy languages, but I will pretend that I am above that). Instead, I just want to examine things that are similar and different about Java and ActionScript 3, and what these characteristics contribute to how we use each language. ActionScript and Java in Antwerp The ideas for this article came straight out of a presentation that James Ward and I gave at the Devoxx conference in Antwerp in December of 2008. James and I played hooky one morning and wrote many of the code examples here over a couple of strong cups of coffee in the hotel lobby. A recording of that presentation should be posted online eventually at the excellent parleys.com Website. (You'll have to go to Antwerp yourself for the hotel coffee, though.)

To compare the two languages, I'll break down their differences into broad categories and look at several examples per category. To keep things manageable, this article is broken into two parts. In this first part I will introduce the topic, start the conversation, and build the kind of tension and suspense that you would expect from any decent multi-part programming discussion. More to the point, I'll cover the following topics: • •



Introduction to ActionScript: Get some context on the platform for which ActionScript is intended: Flash, Flex, and all that. Syntax: Many of the differences between Java and ActionScript 3 are like those highlighted in Figure 1: purely syntactic. The differences are important because you'll certainly hit on them if you try writing an application in Flex, but they needn't really change the way that you think about the language or the way that you solve problems. They are just new tricks for old fingers. Classes: Java and ActionScript 3 employ a similar class structure, but once again the differences are worth discussing. I'll focus on class behavior, which is where the two languages most diverge.

So Part 1 will focus on the basic stuff that any Java developer might be curious about when exploring (or considering) software development for the Flash platform, such as Flex application programming. In Part 2 we'll get into some of the more complex topics and differences between the languages, like properties, dynamic behavior, and functions.

Lights, camera ... ActionScript! ActionScript is the language that is used for programming Flash applications. When users of the Flash authoring tool write code snippets for their program logic, they do so in ActionScript. When developers write programs intended to run on the Flash platform, they do so in ActionScript. And when Flex developers write code using the Flex libraries that produce applications that deploy and run on the Flash platform, they do with ActionScript. But ActionScript has changed over the years. In particular, ActionScript 3 came out in 2006 with FlashPlayer 9 and Flex 2 and represented a significant change in the core language. All of the old capabilities and syntax were still there, but more powerful mechanisms familiar to Java developers were introduced, including classes and packages, types, and a new runtime-compiling VM to handle it all.(Actually, type annotations, classes, and interfaces were available in ActionScript 2, but only as syntactic sugar to be removed at compile time to accommodate the older ActionScript 1 interpreter. ActionScript 3 Integrates these features for real.) Meanwhile, Flex came along a few years ago, and is now at version 3. Flex is a set of libraries that add important functionality like standardized GUI widgets to the Flash platform to make programming powerful Flash applications easier. Flex also adds an XML-based language called MXML that is pre-processed into ActionScript during

compilation. Developers use MXML for the declarative parts of their application, such as what the GUI screens look like, and program in ActionScript directly for their core application logic. I won't cover MXML here because it is not really a part of the ActionScript language itself. I mention it because it comes up in some of the examples and language features that I will discuss later on. I will focus on the modern features of ActionScript, sticking to what ActionScript 3 provides. Many of these features may date back to earlier versions, but to keep things simple I will just assume that we are talking about the latest version, since that is the version that most Flash and Flex developers have access to today. I'll also start using the abbreviation "AS3" to mean ActionScript 3 now, because typing out "ActionScript 3" every time is getting tedious. When I invent a language, I'll start with as short a name as possible. Kernighan & Ritchie did it right.

The wages of syntax I've always thought that one of the most enjoyable activities in life was comparing syntax rules of different languages. Okay, perhaps not. But it is a good place to start when comparing the languages overall, so we'll start with several simple examples of important syntactic differences between AS3 and Java.

Variable declaration Java declares variables like this: public int blah; public Object foo = new Object();

AS3 declares variables like so: public var blah:int; public var foo:Object = new Object();

Variable declaration is where I have tended to bruise my fingers in the Java-to-AS3 migration. After declaring thousands of variables in Java over the years, my fingers know just what (not) to do. And after months of typing hundreds or thousands of declarations in AS3, I still find myself having to go back and add the var keyword, or switch the type definition to live after the variable. It takes some getting used to coming from Java typetyping.

Undefined != null Java has no concept of "undefined": Object foo; Number num;

System.out.println(foo); // outputs 'null' System.out.println(num); // outputs 'null'

AS3 has "undefined", "null", and "NaN" concepts: var foo; var bar:Object; var num:Number; trace(foo); // outputs 'undefined' trace(bar); // outputs 'null' trace(num); // outputs 'NaN'

Note the use of trace() in my AS3 snippets. It's a library difference, not a language difference, so I won't discuss it here. Hopefully it is clear that trace() is the equivalent of System.out.println(). But since outputting to the command-line still ranks as one of the developer's main weapons against bug infestation (right above asking the person in the next cube) I thought I'd at least give a shout out to the lowly trace() statement.

Package declaration Java declares packages in Java source files: package foo; class FooThing { }

AS3 places classes inside package blocks: package foo { class FooThing { } }

These amount to the same thing: they are both ways to organize and control the visibility of global names. One difference is that the Java package declaration is scoped to the whole file so all classes in that file are put into that package, whereas AS3 allows multiple package definitions per file.

Scope Scope in Java is clearly defined as being within the current block: // using i for both is fine – completely separate scopes

public void foo() { for (int i = 0; i for (int i = 0; i }

< 10; ++i) {} < 5; ++i) {}

AS3 variable scope is at the level of the function itself -- regardless of whether the variable is defined within an inner block: // 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 Java has annotations: @Foo public class Bar { @Monkey String banana; }

AS3 has metadata: [Foo] public class Bar { [Monkey] var banana:String; }

Metadata is used for declaring such things as hints to MXML, like the default property to assume when instantiating the class in MXML, and hints for tools, such as default values for properties.

Semicolons Java; requires; semicolons; after; statements;

AS3 does not except; to; separate; multiple; statements; on; a; single; line; But please, on behalf of the readers of your code: use semicolons anyway. After so many years of coding in other languages with line-ending syntax, it just makes code more readable, don't you think?

Final vs. const Java uses the final keyword for constant values: public static final int FOO = 5;

AS3 uses the const keyword: public static const FOO:int = 5;

Casting call Java performs casts by putting the type in parentheses before the object in question: float f = 5; int g = (int)f;

These parenthetical statements always look to me like the code is speaking to me quietly and discretely: "(Hey, psst! You should now consider this float to be an int. Pass it on.)" AS3 casts look more like a function call through the type being cast to: var f:float = 5; var g:int = int(f);

There is also another way of casting in AS3, using the as operator: var g:int = f as int;

Exceptional coding Java typically declares exceptions that are thrown: public void foo() throws MyException { try { // really awesome code } catch (Exception e) {

}

throw new MyException("AAAUUUGGGHHHH!");

}

AS3 throws exceptions without declaration: public function foo():void { try { // really awesome code } catch (var e:Error) { throw new Error("AAAUUUGGGHHHH!"); } }

Generically speaking Java has generics and typed collections: List list = new ArrayList(); list.add(new FooType()); FooType foo = list.get(0);

AS3 ... does not. But AS3 does have typed arrays through the Vector class: var vec:Vector. = new Vector.(); vec[0] = new FooType(); var foo:FooType = vec[0];

Some may wonder at the odd angle-bracket syntax of the Vector declaration. I'm not sure of the history, but I have a feeling that AS3 was just trying to achieve readability and angle-bracket parity with Java's generics.

XML Speaking of angle brackets in code, Java handles XML processing through various libraries (many of them), such as JAXP, JAXB, SAX, Xerces, JDOM, etc. AS3 has E4X integrated into the language itself for queries, manipulation, and the like. var myXML:XML = gable; trace(myXML.Grob); // outputs 'gable'

The next level: Class behavior

As you've seen by now, AS3 classes look pretty much like Java classes. You haven't seen them yet, but AS3 interfaces also look eerily similar to their Java counterparts. But looks aren't everything (except with supermodels and wax fruit) and there are a few important distinctions in behavior that are worth investigating.

Constructors and permissive behavior Java allows the same access permission specifiers (public, protected, private, and package-private) on constructors that are allowed on classes, fields, and methods: public class FooObject { private FooObject() {} } FooObject foo = new FooObject(); // Compiler error

In AS3, constructors are always public: public class FooObject { private function FooObject() {} } // Compiler error

Making a constructor private (in a language that supports it, like Java) is not a typical pattern, although it is helpful in some situations, like creating singletons. If you really want only one of something, then it's a good idea to prevent anyone but the class itself from creating it. A workaround used in AS3 involves throwing exceptions from the constructor when called from outside of your singleton accessor, but it is not quite the same thing.

Interfaces and properties Java allows properties to be declared on interfaces: public interface IFoo { public int blah = 5; public final int VAL = 7; }

*Both of these properties are implicitly static and final, even though they lack those keywords. Try it, you'll see. AS3 does not allow properties on interfaces. Only functions can be declared on interfaces. Note, however, that you can declare properties with set/get functions; just not properties as fields. For example, this works: public interface IProperties {

function set blah(value:Number):void; function get blah():Number; }

If the get/set example here makes no sense, don't worry. You'll learn more about properties and these functions in the second half of this article.

Abstract, what's that? Java allows abstract classes: public abstract class FooObject { public abstract void foo(); }

AS 3 ... does not. There is no concept of "abstract" in AS3.

Related Documents

Java Script For Gpa
July 2019 82
Action Script
November 2019 22
Java Script
April 2020 18
Java Script
July 2020 19
Java Script
November 2019 22