Is this proper in OO theory?

  • Thread starter Daniel Billingsley
  • Start date
D

Daniel Billingsley

The base class obviously can't know anything about a class which inherits
from it, but is it acceptable to have a base class method which will be
given information from an inherited class?

For (a stupid) example:

-----------

public abstract class BaseClass
{
private int _someInteger=0;

protected int AddNumbers(int anotherNumber)
{
return anotherNumber + _someInteger;
}

}

public class Class2 : BaseClass
{
private int _anotherInteger;
public int GetANumber()
{
return base.AddNumber(_anotherInteger);
}
}

----------

The underlying issue is that the generic code in the AddNumbers method from
example is known to be needed in all the classes inheriting from BaseClass,
but needs some additional information based on the specifics of the
inherited class (it's a data access method in reality).
 
M

Marina

I don't feel like I'm getting a clear example of the issue from this
particular code sample.

In general, there is nothing wrong with putting anything in the base class
that will be useful to all its children, even if it requires some
parameters.
 
D

David Browne

Daniel Billingsley said:
The base class obviously can't know anything about a class which inherits
from it, but is it acceptable to have a base class method which will be
given information from an inherited class?

For (a stupid) example:

-----------

public abstract class BaseClass
{
private int _someInteger=0;

protected int AddNumbers(int anotherNumber)
{
return anotherNumber + _someInteger;
}

}

public class Class2 : BaseClass
{
private int _anotherInteger;
public int GetANumber()
{
return base.AddNumber(_anotherInteger);
}
}


Sure that's fine. Although it's more usually implemented using an abstract
method in the base class like this:

public abstract class BaseClass
{
private int _someInteger=0;

protected int GetANumber()
{
return GetAnotherNumber() + _someInteger;
}
abstract int GetAnotherNumber();
}

public class Class2 : BaseClass
{
private int _anotherInteger;
public int GetAnotherNumber()
{
return _anotherInteger;
}
}

So each concrete BaseClass subtype must implemente GetAnotherNumber, which
allows methods implemented in BaseClass to invoke GetAnotherNumber even
though BaseClass does not implement that method.


David
 
D

Daniel Billingsley

You've changed the question a bit, but your answer is very useful
nonetheless. Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top