Search code examples
javagetter-setter

Can anyone tell how can i put getter and setter on the below code, and what exactly getter and setter do


public class perform{

    public static void Main(String args[]) throws IOException 
    {
        perform obj = new perform();
        obj.run();
    }
      public void run() throws IOException 
      {
          String inputfile= "c:/file_adress";
          List<String> field = null;
          String delimeter = ";";
          String line="";
          BufferedReader br = new BufferedReader(new FileReader(inputfile));
          while((line=br.readLine())!=null)
          {
              field = new ArrayList<String>();
              field=Arrays.asList(line.split(delimeter));
              for (String object : field) {

                  System.out.println( "-->" + object + "\n");
              }
          }
      }
      }

now when i try to put getter and setter on this code, by right clickin on the code and then going to source menu. it gives error - "The Operation is not applicable to the current selection. Select a field which is not declared as type variable or a type that declares such fields."

can anyone help me what changes i need to make to add getter and setter and why they are used.


Solution

  • You can add getters and setters for class variables only. In your code, the class is perform and it has two methods - Main() and run(). All the variables you are using in your code and either in Main() or run(). Hence, those are local method variables, and not class variables.

    getter and setter methods allow you to efficiently manage the access of class variables by other external classes. Your local method variables won't be accessed by other external classes. Also, a local variable inside one method cannot be directly accessed in another method, even if it is inside the same class because a local variable is only alive inside the method it is declared.

    Why these are needed? Please read the explanation given in this stackoverflow post - what is the point of getters and setters