Time for action—Declaring some fields

Now, imagine that we want to create a class named Person. Its instances should have a public name field, a private age field, and the class should have a static and public count field.

  1. The first thing we can do is to write it in the following way:
    class Person
    {
    public var name : String; //This one is public
    var age : Int; //This one is private
    public static var count : Int = 0; //This one is static and initialized at 0
    }
    
  2. On the other hand, we can write it by implementing the Public interface, as follows:
    class Person implements Public
    {
    var name : String; //This one is public
    private var age : Int; //This one is private
    static var count : Int = 0; //And this one is public
    }
    

What just happened?

These two solutions will result in exactly the same thing:

  • Without implementing Public: When a class does not implement Public, all of its fields are private by default. That's why we have to explicitly write that the name and count properties are public.
  • When implementing Public: On the other hand, when implementing Public, a class' fields are public by default. That's why we can simply omit the visibility of the name and count fields while we have to explicitly define that the age field is private.

In a block of instructions

The syntax to declare a local variable is slightly different:

var varName [: Type] [= varValue];

As you can see, declaring the type is not mandatory and you can initialize your variable (not depending on anything). The following is a small sample of code, so that you can see how it looks:

class Main
{
public static function main()
{
var myNumber : Int = 15;
}
}

You should know that a variable is available starting from the line where it is declared, until the block it's declared in is closed, and for all blocks inside it.

A variable can be declared several times, either in the same block or in different blocks, as follows:

class Main
{
public static function main()
{
var myNumber : Int = 15;
var myNumber = 2;
trace(myNumber); //Traces 2
{
var myNumber : Int = 1;
trace(myNumber); //Traces 1
}
trace(myNumber); //Traces 2
}
}

As you can see, it is always the closer declaration that is taken into account. That is classical variable hiding. Local variables only live in the block they are defined in.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.119.106