Using Multiple ActionScript 3 Classes

I'm having trouble creating multiple AS3 classes, I've got my document class but can't get other classes.

Below is an example.

~Main.as

package {
    import uk.co.epickris.project.*;

    public class Main {
        public function Main() {
            trace('Main constructor.');
        }
    }
}

~/uk/co/epickris/project/Example.as

package uk.co.epickris.project {
    public class Example {
        public function Example() {
            trace('Example constructor.');
        }
    }
}

After running my flash project, I see the main constructor, but no the example constructor, I'm not sure what I'm doing wrong if anything, any advice would be helpful.

Upvotes: 0

Views: 2792

Answers (1)

Marty
Marty

Reputation: 39456

You need to initialize your Example class by creating an instance of it within the document class.

package
{
    import uk.co.epickris.project.*;

    public class Main
    {
        public function Main()
        {
            trace('Main constructor.');

            // We're creating an instance of the Example class here.
            var eg:Example = new Example();
        }
    }
}

Classes do not automatically have their constructor called when they are imported at the top of a class - instances of classes need to be created with the new keyword.

When the new keyword is used to create an instance, the constructor (defined by creating a function with the same name as the class) will be called as well.

Your document class is the only class in your case that is created and has its constructor called automatically, as that is the nature of a document class.


Please take some time to read this article about the basics of Object-oriented programming in AS3: Introduction to OOP

Upvotes: 1

Related Questions