[04-D2] Package, Class, constructor(생성자), Array(배열)

[01] Package, Class
     - MXML 파일명으로 constructor, extends등 키워드는 사용할 수 없습니다.

1. Package
   - 패키지는 클래스의 집합을 구성합니다.
   - 패키지에 클래스 추가시 폴더를 생성하고 클래스를 추가합니다. (자바와 동일)
   - src 폴더에서 'folder'를 생성하면 패키지가 됩니다.

    예) package parent{                 <-- package 선언
            public class Test{          <-- class 선언
                public function Test(){ <-- 생성자 선언
                }  
            }
        }

        package parent.child{
            public class Test{
                public function Test(){
                }  
            }
        }

    예 2)
       package www.script{
           public class PackTest{
               public function PackTest(){

               }

           }
       }





2. Class, 생성자
   - 변수명과 함수명은 다르게 해야 합니다.

   - method overloading이 없습니다.

   - 접근 제한자
     . internal(default): 같은 패키지 내에서만 접근 가능하며 기본값으로 설정됨
     . public: 모든 클래스에서 접근 가능

   - 클래스 속성
     . dynamic: 실행시에 객체를 생성후 변수 및 메소드 추가 가능.
     . final: 실행시에 변경 불가능.

   - 생성자 오버로딩이 없습니다.
     아래의 생성자는 4가지 유형의 생성자를 지원함, 초기값 자동 할당 지원

     public function Sungjuk(name:String='왕눈이', kuk:int=50, eng:int=50)...

     new Sungjuk();
     new Sungjuk('가길동');
     new Sungjuk('나길동', 90);
     new Sungjuk('다길동', 85, 95);

   - Flex4부터 getter, setter 자동 생성됨.


>>>>> src/www/script/Sungjuk.as
package www.script{
    public class Sungjuk{
        private var name:String = "";
        private var kuk:int = 0;
        private var eng:int = 0;
        private var tot:Number = 0;
        private var avg:Number = 0;
        
        // ---------------------------------------
        // 1. 변수명과 함수명은 다르게 해야 합니다.
        // 2. method overloading이 없습니다.
        // ---------------------------------------
        // 아래의 생성자는 4가지 유형의 생성자를 지원함, 초기값 자동 할당 지원
        // new Sungjuk();
        // new Sungjuk('가길동');
        // new Sungjuk('나길동', 90);
        // new Sungjuk('다길동', 85, 95);
        public function Sungjuk(name:String='왕눈이', kuk:int=50, eng:int=50){
            this.name = name;
            this.kuk = kuk;
            this.eng = eng;
        }
        
        public function total():Number{
            this.tot = this.kuk + this.eng;
            return tot;
        }
        
        public function average():Number{
            this.avg = Math.round(this.avg / 2);
            return this.avg;
        }

        public function getName():String{
            return this.name;
        }
        
        public function setName(name:String):void{
            this.name = name;
        }
        
        public function getKuk():int{
            return this.kuk;
        }
        
        public function setKuk(kuk:int){
            this.kuk = kuk;
        }
        
        public function getEng():int{
            return this.eng;
        }
        
        public function setEng(eng:int){
            this.eng = eng;
        }
            
    }
}




>>>>> class의 사용: SungjukTest.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" creationComplete="init()" width="470">
    <mx:Script>
        <![CDATA[
            import www.script.Sungjuk;
            
            public function init():void{
                var sungjuk:Sungjuk = new Sungjuk();
                var sungjuk2:Sungjuk = new Sungjuk('가길동');
                var sungjuk3:Sungjuk = new Sungjuk('나길동', 90);
                var sungjuk4:Sungjuk = new Sungjuk('다길동', 85, 95); 
                
                // sungjuk 객체의 출력
                var str:String = '';
                str = '성명: ' + sungjuk.getName() + '\n';
                str = str + '국어: ' + sungjuk.getKuk() + '\n';
                str = str + '영어: ' + sungjuk.getKuk();
                
                txaPanel.text = str;
            }
        ]]>
    </mx:Script>
    <mx:TextArea x="10" y="10" width="448" height="372" fontSize="18" id="txaPanel"/>
</mx:Application>







[02] Array(배열)
     - Array의 사용

1. 배열의 사용

>>>>> src/ArrayExam0.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
    layout="absolute" width="321" height="180" 
    creationComplete="init()">
    <!-- creationComplete: 페이지 로딩시 발생하는 이벤트 -->
    <mx:Script>
        <![CDATA[
        
            private var arrayData:Array = new Array(5);
            
            public function init():void{
                txt1.text = '';
                txt2.text = '';
                txt3.text = '';
                txt4.text = '';
                txt5.text = '';
                
                txtInput.text = '';
            }
            
            // 배열의 처음부터 데이터 누적
            public function appendData():void{
                var item:String = txtInput.text;
                // 값이 없는 배열 인덱스에 데이터 입력
                for(var i:int=0; i<arrayData.length; i++){
                    if (arrayData[i] == null){
                        trace(arrayData[i]);
                        arrayData[i] = item;
                        break;
                    }            
                }
                
                displayData();
                
            }
            
            // 마지막 데이터부터 삭제
            public function deleteData():void{
                for(var i:int=4; i >=0; i--){
                    // 값이 있다면
                    if (arrayData[i] != null){
                        arrayData[i] = null;
                        break;
                    }            
                } 
                
                displayData();
            }
            
            public function displayData():void{
                txt1.text = arrayData[0];
                txt2.text = arrayData[1];
                txt3.text = arrayData[2];
                txt4.text = arrayData[3];
                txt5.text = arrayData[4];
            }
            
        ]]>
    </mx:Script>
    <mx:TextInput x="29.5" y="59" width="45" id="txt1" text="txt1" fontSize="18"/>
    <mx:TextInput x="82.5" y="59" width="45" id="txt2" text="txt2" fontSize="18"/>
    <mx:TextInput x="135.5" y="59" width="45" id="txt3" text="txt3" fontSize="18"/>
    <mx:TextInput x="188.5" y="59" width="45" id="txt4" text="txt4" fontSize="18"/>
    <mx:TextInput x="241.5" y="59" width="45" id="txt5" text="txt5" fontSize="18"/>
    
    <!-- 입력 목적 콘트롤 -->
    <mx:TextInput x="22.5" y="117" width="63" id="txtInput" text="txtInput" fontSize="18"/>
    
    <mx:Button x="93.5" y="117" label="입력 수 추가" fontSize="18" id="btnAppend" click="appendData()"/>
    <mx:Button x="234.5" y="117" label="삭제" fontSize="18" id="bntDelete" click="deleteData()"/>
    <mx:Label x="29" y="10" text="Array Test" fontSize="18" fontFamily="Verdana"/>
</mx:Application>





2. 배열의 선언 및 사용 

>>>>> src/ArrayExam1.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" width="487" height="412">
    <mx:Script>
        <![CDATA[
            private function arrayExam():void {
                // [] : Array 원소를 한 번에 초기화 
                var myArr:Array = ["a", "b", "c"];
                for (var i:int=0; i<myArr.length; i++) {
                    ta.text += 'myArr[' + i + ']: ' + myArr[i] + '\n';
                }
                
                // [] : Array 초기화후 개별 원소값 세팅 
                var myArr2:Array = new Array();
                myArr2[0] = "A", myArr2[1] = "B", myArr2[2] = "C";      
                
                var j:int = 0;
                for each (var elm:* in myArr2) { // * 데이터형 생략
                    ta.text += 'myArr2[' + j + ']: ' + elm + '\n';
                    j++;
                }
                
                ta.text += "\n객체의 출력\n";           
                // {x:y} 키:값형식 연산자로써  Object 초기화 
                // 객체의 출력
                // myObj[name]: 개발자
                // myObj[address]: 대한민국
                // myObj[program]: flex 3
                var myObj:Object = {name:'개발자', address:'대한민국', program:'flex 3' }; 
                for (var key:String in myObj) {
                    ta.text += 'myObj[' + key + "]: " + myObj[key] + '\n';
                }
                
                ta.text += myObj.name + '\n';
            }
        ]]>
    </mx:Script>
    <mx:Button label="배열 실습" click="arrayExam()" fontSize="18"/>
    <mx:TextArea id="ta" width="425" height="326" fontSize="18"/>       
</mx:Application>



    

3. 배열의 조작
   - push: 배열의 끝에 데이터 추가가 되며 배열의 사이즈가 변경됩니다.
   - unshift: 배열의 처음에 데이터가 추가 되며 배열의 사이즈가 변경됩니다.

>>>>> src/ArrayExam2.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="480" height="320">
    <mx:Script>
        <![CDATA[
            public function showStrings():void{
                var arr:Array = new Array(5);

                // 저장된 배열값: 0 1 2 3 4
                for(var i:int=0; i<5; i++){
                    arr[i] = i;
                }
                
                /*
                 push: 배열의 끝에 데이터 추가가 되며 배열의 사이즈가 변경됩니다.
                 unshift: 배열의 처음에 데이터가 추가 되며 배열의 사이즈가 변경됩니다.
                 */
                // 저장된 배열값: 0 1 2 3 4 날짜: 24                
                arr.push("오늘 날짜: " + new Date().getDate() + " 일");
                
                // 배열의 맨앞 index 0에 요소 추가
                // 저장된 배열값: FLEX TEST 0 1 2 3 4 날짜: 24
                arr.unshift("FLEX TEST ");
                
                for(var j:int=0; j<arr.length; j++){
                    txtResult.text += arr[j].toString();
                    txtResult.text += "\n";
                }               
            }
        ]]>
    </mx:Script>    
    <mx:Button x="207.5" y="288" label="Button" click="showStrings()"/>
    <mx:TextArea x="8" y="10" width="462" height="270" id="txtResult" fontSize="20"/>
</mx:Application>




    
[과제] 아래의 Notice.mxml 파일을 참조하여 ActionScript class를 작성하세요.

>>>>> DTO: NoticeDTO.as
package www.notice{
    public class NoticeDTO{
        private var no:int = 0;
        private var title:String = "";
        private var date:String = "";
        
        // 생성자
        public function NoticeDTO(no:int = 0,  title:String="[공지] "){
            this.no = no;
            this.title = title;
            var dateObj:Date = new Date(); 
            this.date = dateObj.getFullYear() + "-"+(dateObj.getMonth()+1) + "-" + dateObj.date;           
        }
        
        public function getNo():int{
            return this.no;
        }
        
        public function getTitle():String{
            return this.title;
        }
        
        public function getDate():String{
            return this.date;   
        }
        
        public function setNo(no:int):void{
            this.no = no;
        }
        
        public function setTitle(title:String):void{
            this.title = title;
        }
        
        public function setDate(date:String):void{
            this.date = date;
        }

    }
}




>>>>> Manager: NoticeMgr.as
package www.notice{
    public class NoticeMgr{
        
        private var registry:Array = null;
        
// 생성자에서 배열 생성 
        public function NoticeMgr(){
            this.registry = new Array();
        }
        
// 배열에 객체 저장 
        public function create(dto:NoticeDTO):void{
            registry.push(dto);
        }
        
// 배열에서 객체 추출 
        public function read():NoticeDTO{
            return NoticeDTO(registry.pop()); // 배열에서 요소 제거
        }
        
// 갯수 리턴 
        public function count():int{
            return registry.length;   
        }

    }
}




>>>>> Notice.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="623" height="393">
    <mx:Script>
        <![CDATA[
            import www.notice.NoticeDTO;
            import www.notice.NoticeMgr;
            
            private var dto:NoticeDTO;
            private var mgr:NoticeMgr = new NoticeMgr();   
            
            public function evtCreate():void{
                var dto:NoticeDTO = new NoticeDTO(int(txtNo.text), txtTitle.text);
                mgr.create(dto);
                
                txtNo.text = '';
                txtTitle.text = '';
            }
            
            public function evtPrint():void{
                var count:int = mgr.count();
                var str:String = "";
                for(var i:int = 0; i<count; i++){
                    var nd:NoticeDTO = mgr.read();
                    str = str + '번호: ' + nd.getNo();
                    str = str + ' / 제목: ' + nd.getTitle();
                    str = str + ' / 날짜: ' + nd.getDate() + "\n";
                }
                
                txaPanel.text = str;
            }
                    
        ]]>
    </mx:Script>
    
    <mx:TextArea x="42" y="28" width="533" height="163" fontSize="18" id="txaPanel"/>
    <mx:Form x="42" y="199" width="533" height="115">
        <mx:FormItem fontSize="18" label="번호: ">
            <mx:TextInput id="txtNo" width="278"/>
        </mx:FormItem>
        <mx:FormItem label="제목: " fontSize="18">
            <mx:TextInput id="txtTitle" width="276"/>
        </mx:FormItem>
    </mx:Form>
    <mx:Button x="189" y="332" label="데이터 추가" fontSize="18" id="btnCreate" click="evtCreate()"/>
    <mx:Button x="335" y="332" label="데이터 출력" fontSize="18" id="btnPrint" click="evtPrint()"/>
    
</mx:Application>



Posted by ▶파이팅◀

블로그 이미지
Let's start carefully from the beginning
▶파이팅◀

태그목록

공지사항

Yesterday
Today
Total

달력

 « |  » 2024.4
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

최근에 올라온 글

최근에 달린 댓글

글 보관함