Reputation: 71
OK I've got some question about what I guess is basic OOP. For example, let's say I have many diffrent objects which has diffrent classes. Let's say, one object called, car (Car.as), then I have a truck (truck.as) and a moped (moped.as). Now instead of writing a simple function within all of these, can't I have a class and then attach this function onto everyone of these objects?
For example I want them to be able to fade out. Then I have a class called "AlphaThings" and within this class I write a simple fadeout function.
Can't I somehow then attach this function to another object? Like
AlphaThings.fadeout(car);
AlphaThings.fadeout(truck);
AlphaThings.fadein(moped);
Thanks, and sorry if there some misspelled words.
Upvotes: 1
Views: 103
Reputation: 39476
You're trying to accomplish inheritance, which is where a class inherits properties and methods from another.
Inheritance is accomplished by using the extends
keyword when defining the class.
Your three objects Car
, Truck
and Moped
could inherit from (extend) AlphaThings
like this:
class Car extends AlphaThings
{
//
}
Your Car
will now contain all of the properties and methods defined within AlphaThings
, such as .fadein()
and .fadeout()
that you mentioned.
Bonus info:
When you extend another class, you can alter how methods existing within the base class will work in the class inheriting from it. This is done using the override
keyword.
For example, you may want your Car
to do something slightly different or additional when you use .fadein()
on it, so you would override that method like this:
override public function fadein():void
{
// Some additional logic.
// ...
super.fadein();
}
The line super.fadein()
is there to call the original .fadein()
function. If you omit this, you can completely rewrite the function and have the previously defined actions ignored.
Regarding this specific scenario:
This answer of course gets straight to the point and answers the question directly by explaining how to achieve inheritance. With that said, what you're trying to achieve can be done more cleanly using one of a handful of other routes.
For example, consider this Tweening Library by Greensock. The library can deal with the transitioning of any values (including alpha) on any objects in different ways. Here are some examples of why this is great vs using inheritance:
AlphaThings
from your example to use it.AlphaThings
in a new project.Upvotes: 4
Reputation: 3830
You would declare the behavior you want in a parent class, then derive Car, Truck and Moped from that. They'll then get the methods.
The following link explains it in more detail: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7fcd.html
Upvotes: 1