Reputation: 1926
I have a class A which has become too long. So I have decided to move some of its functions to class B. I have made B inherit from A.
Now there are functions in A, which need functions in B. My question is where should I instantiate class B in class A. I cannot instantiate in the class A constructor, because class B will call the base class to create a never ending loop.
I only want class B to be instantiated once, because class A constructor has object which I only want to initialise once.
I am not even sure if I am making any sense now.
Upvotes: 0
Views: 1282
Reputation: 67336
You should only use inheritance if there is a true "is-a" relationship. To me, it sounds like you are describing functionality that class B needs. Perhaps B "has-a" A so you should consider composition instead of inheritance:
public class B
{
private A a;
public B(A a)
{
this.a = a;
}
public void UseAFunction()
{
a.MyFunction();
}
}
Upvotes: 1
Reputation: 28802
If you make the functions abstract in A
(this will have to make A
abstract too), then just call those methods from A
's methods as you would normally. Then override the abstract functions in B
with the logic you want. When the user instantiates the B
class those calls will translate to calls in B
even if the compile time type of the variable holding the instance is A
.
Upvotes: 1
Reputation: 1234
The base keyword lets you access the superclass (baseclass): http://msdn.microsoft.com/en-us/library/hfw7t1ce(v=vs.71).aspx
BUT: If your only concern is the length of a class, it might be a better solution to use partial classes (http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.80).aspx). You can split up your class into multiple files. Obviously what you are doing right now is not the intention and meaning of inheritance.
Upvotes: 3
Reputation: 921
First of all its not best practice to define a new class when your class becomes too long. IF all functionality is logically related to the same object you can keep it in the same class no matter how long it is.
If you want B to be instantiated only once you should make it a static class. You can find more info about static classes in here: http://msdn.microsoft.com/en-us/library/79b3xss3(v=vs.80).aspx
Upvotes: 1
Reputation: 51684
Inheritance is heavily overused. Especially in your case you want to prefer composition over inheritance.
Upvotes: 4