views:

346

answers:

3
package a{
 public class a{
    public var a_var:String;
     public var x_var:String;
    public function a(){
     var a_var = 'My name';
     var  x_var = 'X string'
     }
    public function show_a():String{
     return a_var;
     }  

     }

public class b{

    public function b(){
     var a_obj:a = new a();
     trace('trace' + a_obj.a_var ); //is this wrong?
     trace(a_obj.show_a()); //is this possible then what would be the out put?
     }


     }  
}

Hi all i want to get the variables from class a to class b. The above code is not working :( . It return the null values from the class a :(..

or any other method??

+1  A: 

In your class a constructor replace:

public function a() {
    var a_var = 'My name';
    var x_var = 'X string'
}

with:

public function a() {
    this.a_var = 'My name';
    this.x_var = 'X string'
}

Keyword var creates local variable in contructor so that variable get garbage collecteded after flow gets out of contructor.
By using this you assign value to instance variable which is what you want in that case.

kret
A: 

It is because in the constructor of a, you are not assigning to the class fields a_var and x_var. You are declaring indentically named variables that have local scope and fall out of scope at the end of the constructor block. Try removing the var from the starts of these 2 lines:

var a_var = 'My name';
var  x_var = 'X string'

...and all will be good.

spender
A: 

You can't have more than once class inside a package{} declaration. Either split them into two files or take one class out of the package{} and remove its public access modifier.

//A.as
package a
{
  public class A
  {
    //constructor and stuff
  }
}
class B
{
  //class B goes here
}

or

//A.as
package a
{
  public class A
  {
    //constructor and other stuff
  }
}
//B.as
package a
{
  public class B
  {
    //constructor and other stuff
  }
}

And yeah, as spender pointed out, u have to remove the var declaration from the constructor.

Amarghosh
yes its in separete file n i just put that for demonstrate..
coderex