Reputation:
Yeah, sorry about asking a stupid n00b question. So I have a C# program. I have a class
class foo
{
public int bar, wee, someotherint, someyetanotherint;
public foo()
{
this.bar = 1:
this.wee = 12;
this.someotherint = 1231;
this.someyetanotherint = 443;
}
}
And I want to make a class called spleen that inherits from foo
class spleen : foo
{
}
What is the quickest, easiest syntax to make the class spleen inherit the constructor from foo without having to copy/paste the entire constructor from foo? I don't want to hear that I already have too many parameters. I already know that. (edit: Actually, no. I'm an idiot) I know I should probably somehow call the parent constructor, but I don't know how. How do I do that.
Edit: I realize now that I should have taken more time to write my question. It looks like I was trying to ask two questions at the same time without realizing it (how to inherit constructors with no parameters, and how to inherit constructors with parameters) , and somehow jumbled it all up. However the answers provided were very helpful and solved my problem. Thanks, and sorry for being such an idiot!
Upvotes: 7
Views: 15463
Reputation: 754655
What you're looking for is the base keyword. You can use it to call into the base constructor and provide the necessary arguments.
Try the following. I picked 0 as a default for lack of a better option
class spleen : foo {
public spleen() : base(0,0,0,0)
{
}
}
EDIT
Based on your new version of the code, the simplest way to call the constructor is to quite literally do nothing. The default constructor generated for spleen will automatically call the base empty constructor of foo.
class spleen : foo {
public spleen() {}
}
Upvotes: 19
Reputation: 573
JaredPar is right but missed something and I don't have enough rep to edit it.
class spleen : foo
{
public spleen() : base()
}
If you parent class took in parameter in the constructor then it would be
class foo
{
public int bar, wee, someotherint, someyetanotherint;
public foo(int bar, int wee, int someotherint, int someyetanotherint)
{
this.bar = bar;
this.wee = wee;
this.someotherint = someotherint;
this.someyetanotherint = someyetanotherint;
}
}
class spleen : foo
{
public spleen(int bar,
int wee,
int someotherint,
int someyetanotherint) : base(bar,
wee,
someotherint,
someyetanotherint)
}
Upvotes: 5
Reputation: 61
Make the constructor protected:
protected Operator(String s, int i, boolean flag){
operator = s;
precedenceLevel = i;
associative = flag;
}
//stuff
class MulOperator extends Operator {
protected MulOperator(String s, int precedenceLevel, boolean flag) {
super(s, precedenceLevel, flag);
}
so on and so forth
EDIT: Assuming they have the same/similar constructor...
Upvotes: -3
Reputation: 564403
You just create it, and call the base constructor:
public spleen(int bar, int wee, int someotherint, int someyetanotherint)
: base(bar,wee,someotherint,someyetanotherint)
{
// Do any spleen specific stuff here
}
Upvotes: 7