0

So, can I use same name for public variable in a class and method argument in java? for example("number" is declared twice):

public class Class1 {
    public int number;

    public static String function1(String id,int number)
    {
        //do something

    }
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Nfff3
  • 321
  • 8
  • 24

4 Answers4

3

Yes, you can because the two variables are in different scopes. The method argument is hiding the class attribute for the scope of the function. If you want to access the class attribute within your method anyway, simply use this.number instead.

Tim
  • 287
  • 1
  • 13
1

Yes, if anyhow you have scope related problem then you can qualify the member using the reference this

public static String function1(String id, int number)
{
    this.number = number; 
    //here you assign the class member with the value of the parameter
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

Yes you can.

The int number declared in the method is only accesible inside de method.

The int number declared as property in the class is accesible in any method for the class.

If you want to access to the number property inside the method, you must use this.

Example:

public static String function1(String id,int number)
{
    this.number = number;
}
melli-182
  • 1,216
  • 3
  • 16
  • 29
  • 1
    Please modify "If you want to access to the number variable inside the method" to "If you want to access to the number property inside the method" because the two are variable. People can get confused in my opinion :) The same in this phrase "If you want to access to the number variable inside the method, you must use this." change to property :) – Ramon Schmidt May 31 '17 at 13:57
-1

Yes you can use same name for public variable and method argument in java but be careful in case of constructor

You cannot do like this

public class Car{
    String carname;
    int carspeed;

    public  Car(String carname , int carspeed){
        carname = carname;
        carspeed = carspeed;
    }

}

instead do this

public class Car{
    String carname;
    int carspeed;

    public  Car(String carName , int carSpeed){
        carname = carName;
        carspeed = carSpeed;
    }

}

or do this

public class Car{
    String carname;
    int carspeed;

    public  Car(String carname , int carspeed){
        this.carname = carname;
        this.carspeed = carspeed;
    }
}

even you can mix it

 public class Car{
        String carname;
        int carspeed;
    
        public  Car(String carname , int carSpeed){
            this.carname = carname;
            carspeed = carSpeed;
        }
    }

when you use same variable name for parameter inside constructor and your class property name then they throw error at compile time

Harsh Mangalam
  • 1,116
  • 1
  • 10
  • 19