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 trial

C# C# Objects Methods Method Overloading

Ali Dahud
Ali Dahud
3,459 Points

There are two questions...

Firstly doesn't a method overloading make the first method redundant? because in this case, it makes it redundant.

Second, why don't we just initialize the parameters of the methods as fields I mean why don't we just make

public readonly int FlyReactionTime;
public readonly int DistanceToFly;

public Frog (int distanceToFly,int flyReactionTime, ...)
{
    FlyReactionTime=flyReactionTime;
    DistanceToFly=distanceToFly;
    ...
}

instead of this

public bool EatFly (int distanceToFly, int flyReactionTime)
{
    ...
}
Frog.cs
namespace Treehouse.CodeChallenges
{
    class Frog
    {
        public readonly int TongueLength;
        public readonly int ReactionTime;
        public Frog(int tongueLength, int reactionTime)
        {
            TongueLength = tongueLength;
            ReactionTime=reactionTime;
        }

        public bool EatFly(int distanceToFly)
        {
            return TongueLength >= distanceToFly;
        }
        public bool EatFly(int distanceToFly, int flyReactionTime)
        {
            return TongueLength >= distanceToFly    && ReactionTime <= flyReactionTime;

        }
    }
}

Steven Parker

1 Answer

Steven Parker
Steven Parker
231,248 Points

The reason overloading isn't redundant is because the overloaded methods must have a different signature. That means that they will take a different number of arguments, or different types of arguments, or return a different type of value, or some combination of these differences.

And the reason that you would not require method arguments in the constructor is that they may be used more than once on different values. For this example, the frog might attempt to eat several different flies in its lifetime, but if a specific fly distance and speed were part of the constructor, that's the only fly it could (try to) eat.