Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
216,083 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.