-3

I know that my question is a bit bizarre but I can't wrap my head around it.
Subject:
I've a class and fields declared before constructor and I need constructor as well, say:

class Fields
{
    private int field1;
    Fields(int field1)
    {
        this.field1 = field1;
    }
}

This one above makes sense to me. Now, the code below, I've seen that kind of code somewhere

class Fields
{
    Fields(int field1)
    {
        //some code here
    }
}

Question:
Why would someone need the second option without declaring fields outside a constructor?

Thanks!

Vlad
  • 181
  • 2
  • 10
  • What does the second example do with `int field1`? I'd assume it is used for something – UnholySheep Mar 25 '18 at 22:29
  • 1
    Yep, your question is not fully clear. Please post a real-world real-code example of exactly what you mean. – Hovercraft Full Of Eels Mar 25 '18 at 22:33
  • 1
    Are you asking why you'd have a parameter in the constructor whose value isn't assigned to a field? – Sotirios Delimanolis Mar 25 '18 at 22:35
  • Possible duplicate of [What is the difference between a local variable, an instance field, an input parameter, and a class field?](https://stackoverflow.com/questions/20671008/what-is-the-difference-between-a-local-variable-an-instance-field-an-input-par) – Kristin Mar 25 '18 at 22:40
  • There are many reasons you might pass an argument to a constructor that isn't directly assigned to a field. Please provide a more concrete example if you want a concrete answer. – shmosel Mar 25 '18 at 22:58
  • @SotiriosDelimanolis yes, that's the question! why would one uses a constructor with a parameter without a field? Under what circumstances it would be useful at all? – Vlad Mar 25 '18 at 23:25
  • @shmosel couldn't come up with any concrete example, that's why I called it bizarre. Could you please give at least a bit of a general flavor on why someone uses parameter without a direct assignment to a field? Thanks! – Vlad Mar 25 '18 at 23:41
  • Well of course it's bizarre in the form you've presented it. But you haven't seen that actual snippet anywhere, have you? – shmosel Mar 25 '18 at 23:42
  • @shmosel I've seen it in one of the Android apps but sadly couldn't recollect where and what. Any idea re why it can be used? – Vlad Mar 26 '18 at 13:40
  • Again, there can be many reasons. The question is too broad. – shmosel Mar 26 '18 at 16:36

1 Answers1

0

Your question is not so much clear. But I think that you are asking about constructor and its mechanism. A constructor is usually used inside a class to initialize data for several variables.

Your second example has one parameter that makes no sense according to your code. It's useless. On the other hand, you can declare parameter but you will use it or not its depend on you. Best practice is skipping unused parameters

Ariful Islam
  • 696
  • 6
  • 11