Designer parameters



  • 1.

    public class TestEmployee {
        public static void main(String[] args) {
            String name = "larry";
            Employee harry = new Employee(name);
        }
    }
    class Employee {
        String name;
        public Employee(String n) {
            name = n;
            System.out.println("constructor");
        }
    }
    

    2.

    public class TestEmployee {
        public static void main(String[] args) {
            String name = "larry";
            Employee harry = new Employee(name);
        }
    }
    class Employee {
        String name;
        public Employee(String name) {
            System.out.println("constructor");
        }
    }
    

    I can't understand a simple thing. In the construction of objects, arguments are given in brackets. Depending on these arguments, the necessary designer is selected. The textbook gives an example of the first leaflet. Why indicate a reference nWhen you can just write name and call the same designer?



  • The exact design parameter (as opposed to type) does not play a role. In the second leaflet, the value given in the parameter will not be recorded in the field of Employee. Add the field display challenge name After the creation of copies of the class in each case, for example, in the second case:

    public class TestEmployee {
        public static void main(String[] args) {
            String name = "larry";
            Employee harry = new Employee(name);
            System.out.println(harry.name);
        }
    }
    class Employee {
        String name;
        public Employee(String name) {
            System.out.println("constructor");
        }
    }
    

    In order to visually distinguish the name of the parameter and the name of the class field, the parameter was called nHe could also be named and nameBut then visually it would be hard to tell where. In any case, the compiler would have successfully dismantled such a design and co-compiled the class.

    The main point is that you must understand from this example: Just by calling the design parameter like the class field, you don't get automatic attribution.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2