accessing parent variables

  • Thread starter Thread starter Rustam Asgarov
  • Start date Start date
R

Rustam Asgarov

how can i access variables defined in the parent class from the child class:
By some way other than passing as parameter to constructor.

I mean.

class Parent{

public int b;

public Method()
{
b = 5;
Child child = new Child();
}

}

class Child{

public Method()
{
int a = b; // to do this..
}
}
 
In your case, you have a HAS-A relationship (and not a parent-child or IS-A
relationship). The only way to have the child making access to public
members of your "Parent" class is either to pass the member(s) in the
ctor/methods or better to pass the "this" of Parent in the ctor of your
"Child"

José
 
Rustam Asgarov said:
how can i access variables defined in the parent class from the child class:
By some way other than passing as parameter to constructor.

I mean.

class Parent{

public int b;

public Method()
{
b = 5;
Child child = new Child();
}

}

class Child{

public Method()
{
int a = b; // to do this..
}
}

I don't think it is possible. What if I defined:

class OtherParent
{
private Child _myChild;

public OtherParent(Child theChild)
{
_myChild = theChild;
}
}

Which "parent" should be used now?

By the way: "child classes" usually refers to classes that are defined (as
opposed to "used")
inside some parent class. Like:

class Parent
{
class Child
{ ... }

...
}

In this case "Child" CAN refer to fields (even private!) of "Parent".


Hans Kesting
 
Back
Top