kornben
kornben

Reputation: 45

Calling a parent class from a subclass

class experiment
{

    int xCoord = 0;
    int yCoord = 0;

    public experiment(int x, int y) {
        this.xCoord = x;
        this.yCoord = y;
    }
}

class result :experiment{
    int zCoord = 0;

    public result(int z) : base(x,y) 
    {
        this.zCoord = z;
    }

}

Can anyone help me solve this simple problem. I'm having an error base(x,y) it says the name 'x' does not exists in the current context and also goes for the y.

Upvotes: 2

Views: 80

Answers (2)

Habib
Habib

Reputation: 223237

x and y are local fields to class experiment they are not visible in inherited class, you may call the base constructor with default values like:

public result(int z) : base(0,0) 

Also please follow General Naming Conventions from Microsoft, so the class names begins with upper case character.

EDIT:


It would be better if your child class has a constructor to receive parameter x and y, and the it calls the base class constructor with those values like:

public result(int x, int y, int z) : base(x,y) 
{
    this.zCoord = z;
}

Upvotes: 8

dev hedgehog
dev hedgehog

Reputation: 8791

There is no x,y in constructor of result class.

You pass to your constructor z but tell your base constructor to recieve x and y. Though there are no x and y at that time.

Try this:

public result(int z, int x, int y) : base(x,y) 
{
    this.zCoord = z;
}

Or set fix values (no variables):

public result(int z) : base(0, 0) 
{
    this.zCoord = z;
}

Upvotes: 4

Related Questions