Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMula Goa
Courses Plus Student 1,387 PointsIs it required to pass the super class parameter for the subclass it is inheriting from?
So I haven been learning Java for a while but decided to switch to C#. It's been a while so I may forget some things. What I know is that in Java, when inheriting from a super class you can or can not call the super class and pass in the parameter if it accepts it. For example:
public class Super{
public Super(int x)
{
}
}
public class Sub extends Super
{
public Sub()
{
super(5);
}
}
and then this other example:
public class Super
{
public Super(int x)
{
}
}
public class Sub extends Super
{
public Sub()
{
}
}
is also totally fine since it does not have to pass in parameter to the superclass, correct me if I am wrong. But then in C#, I am not sure if you are required to pass in the parameter for the superclass or not(like if it is still legal and won't cause any problem)
1 Answer
Steven Parker
231,248 PointsIn C#, you would pass the required parameter using a slightly dfferent syntax and the keyword "base": instead of "super".
But you're getting ahead of things, you'll see this discussed in the courses.
Mula Goa
Courses Plus Student 1,387 PointsMula Goa
Courses Plus Student 1,387 PointsI am asking if it is required to call the base class. I know how to call the base class.
Steven Parker
231,248 PointsSteven Parker
231,248 PointsIt's required if the only constructor in the base requires an argument. It would be optional if the base class has overloaded constructors, one that takes an argument and one that does not.
Mula Goa
Courses Plus Student 1,387 PointsMula Goa
Courses Plus Student 1,387 PointsSo if the base constructor doesn't require an argument, do we put : base() or you can just omit that from the code. And also if the base class overloaded but all of them(constructor) required parameter then we must at call one constructor and pass in the argument, am I correct?
Steven Parker
231,248 PointsSteven Parker
231,248 PointsYou are correct, and you can omit the "
: base(
arg)
" entirely when no argument is being passed.Mula Goa
Courses Plus Student 1,387 PointsMula Goa
Courses Plus Student 1,387 PointsThank you so much for your help and clarifying. I am new learning C#, so syntax is a bit different from Java.