01 July 2010

Simple AS3 Data Structure - part II

Student data structure from previous post doesn't have to be created like I have shown earlier. There is one more OOP way of doing it, to create a class. Private variables will hold particular information and we can use getters and setters to assign and retrieve values.

Here is the code for Student.as class:



package
{
public class Student
{
private var _name:String;
private var _age:uint;
private var _grades:Array;

public function Student (sName:String):void
{
_name = sName;
}

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

public function get name ():String
{
return _name;
}
public function set age (studentAge:uint):void
{
_age = studentAge;
}

public function get age ():uint
{
return _age;
}

public function set grades (studentGrades:Array):void
{
_grades = studentGrades;
}

public function get grades ():Array
{
return _grades;
}

public function getAverage():Number
{
var sum:Number = 0;
for (var j:uint = 0; j < grades.length; j++) {
sum = sum + grades[j];
}
return sum / grades.length;
}
}
}



As you may noticed there is built-in getAverage function to make things easier. Now, you can test this class functionallity by creating TestStudent.fla in same directory where you saved Student.as file. In first frame of the TestStudent file enter next code:



import Student;

var student1:Student = new Student("John");
student1.age = 22;
student1.grades = [4, 5, 5, 3];

var student2:Student = new Student("Ella");
student2.age = 20;
student2.grades = [4, 5, 5, 4, 5];

var average:Number = student1.getAverage();
trace(average);

average = student2.getAverage();
trace(average);



Which method you will use depends on your needs and style.

*_*

2 comments:

Mark said...

Why not creating a getter called avarage, instead of a function called getAvarage?

flanture said...

hi Mark, I wanted to make a distinction between simple data like name, age, grades and function which uses those data to create new value (in this case average grade).

 

template by blogger templates