2009年8月19日 星期三

ActionScript 3.0繼承使用範例

Interface IAction
package com
{
/**
* ActionScript3 interface
* 在Actionscript3的介面中不可使用存取修飾子 

  * public protected private
*/


public interface IAction
{
 //加速
 function speedUp():void;
 //減速
 function slowDown():void;
 //發出聲響
 function makeSound():String;
}


PS.介面方法都是public


Class Car
package com
{
/*
* Actionscript 並沒有抽象類 宣告 ,因此第一個class就必須實踐interface,
* 如果想做類似java的抽象Class Car 就不要寫入程式碼來模擬。
*/

public class Car implements IAction
{

 private var _speed:int;
 private var _name:String;

 public function Car()
 {
  _name = "Car";
 }

 public function get name():String
 {
   return _name;
 }

 public function set name(value:String):void
 {
  _name = value;
 }

 public function get speed():int
 {
  return _speed;
 }
 public function set speed(value:int):void
 {
  _speed = value;
 }

 //實踐interface但不撰寫程式碼
 public function speedUp():void
 {
 }

 //實踐interface但不撰寫程式碼
 public function slowDown():void
 {
 }

 //實踐interface但不撰寫程式碼
 public function makeSound():String
 {
  return"";
 }

 public function skill():String
 {
  return "";
 }
}
}




Class AE86

package com
{
public class AE86 extends Car
{
private var _name:String;

public function AE86(name:String)
{
 super();
 _name = name; 
}

override public function speedUp():void
{
 this.speed = this.speed + 10;
 //super.speed = super.speed + 10;
}

override public function slowDown():void
{
 super.speed = super.speed -10;
}

override public function makeSound():String
{
 return "轟轟轟";
}

override public function skill():String
{
 return "水溝蓋過彎";
}


/*
* 這個getName有override Car的 getName 
*/
override public function get name():String
{
 return super.name + " IS " + this._name;
}

override public function set name(value:String):void
{
 this._name = value;
}
}
}

InheritExample
package
{
import com.AE86;
import com.Car;

import flash.display.Sprite;
import flash.text.TextField;

public class InheritExample extends Sprite
{
//顯示欄位
private var t:TextField;

private var car:Car;
private var ae86:AE86;

public function InheritExample()
{
super();

t = new TextField();
t.multiline = true;
t.text = "";
t.width = 1280;
t.height = 900;
this.addChild(t);

car = new AE86("AE86-1");
ae86 = new AE86("AE86");

t.text += car.name  + '\n';
t.text += ae86.name +'\n';
t.text += "--------------\n";

t.text += car.makeSound() + '\n';
t.text += ae86.makeSound() + '\n';
t.text += "--------------\n";

//水溝蓋過彎
t.text += car.skill() + '\n';
t.text += ae86.skill() + '\n';
t.text += "--------------\n";




t.text += car.speed  + '\n';
t.text += ae86.speed + '\n';
t.text += "--------------\n";

//加速
car.speedUp();
ae86.speedUp();

t.text += car.speed  + '\n';
t.text += ae86.speed + '\n';
t.text += "--------------\n";


car.slowDown();
ae86.slowDown();

t.text += car.speed  + '\n';
t.text += ae86.speed + '\n';
}
}
}



輸出:
Car IS AE86-1
Car IS AE86
--------------
轟轟轟
轟轟轟
--------------
水溝蓋過彎
水溝蓋過彎
--------------
0
0
--------------
10
10
--------------
0

0

沒有留言:

張貼留言