简体   繁体   English

何时在Java中使用参数化方法与参数化构造函数

[英]When to use Parameterized Method vs Parameterized Constructor in Java

I have just started learning Java and came to this topic of Parameterized method and Parameterized constructor from Java Ninth Edition Herber Schildt[chapter 6] , 我刚刚开始学习Java,并从Java第9版Herber Schildt [第6章]中谈到了参数化方法和参数化构造函数的主题,

I understood how to declare them and how do they work, but I am confused about their usages, when to use Parameterized Method and when to use parameterized constructor? 我了解如何声明它们以及它们如何工作,但是我对它们的用法, 何时使用参数化方法以及何时使用参数化构造函数感到困惑

Please give me an example with simple analogy. 请给我一个简单类比的例子。

They have a main difference which is the return type. 它们的主要区别在于返回类型。 A constructor doesnt return anything , not even void. 构造函数不返回任何内容,甚至不返回void。 A constructor is run when a class is instantiated. 实例化类时,将运行构造函数。 On the other hand, parameterized methods are used for type safety, ie to allow different classes without casting. 另一方面, 参数化方法用于类型安全,即允许不同的类而无需强制转换。

 public class Person {

        String name ;
        int id;

//Default constructor
        Person(){

        }

//Parameterized constructor
        Person(String name, int id){
            this.name = name;
            this.id = id;

        }

        public static void main(String[] args) {
            Person person = new Person("Jon Snow",1000); // class instantiation which set the instance variables name and id via the parameterised constructor

            System.out.println(person.name); //Jon Snow
            System.out.println(person.id); //1000

            Person person1 = new Person(); //Calls the default constructor and instance variables are not set

            System.out.println(person1.name); //null
            System.out.println(person1.id); //0
        }

    }

First of all you should understand what the constructor actually means. 首先,您应该了解构造函数的实际含义。

You can consider "Constructor" as a function that gets called whenever you create an object for a class. 您可以将“构造函数”视为当您为类创建对象时就会调用的函数。 Inside a class you can have many instance variables ie Every object of that class will have its own copy of its instance variables. 在一个类中,您可以有许多实例变量,即该类的每个对象都有其实例变量的副本。 Thus whenever you create a new object using the new ClassName (args) statement, you can initialize the values of the instance variables of that object within the constructor since it will be called first whenever you instantiate an object. 因此,每当使用new ClassName (args)语句创建新对象时,都可以在构造函数中初始化该对象的实例变量的值,因为在实例化对象时将首先调用该对象。 Remember constructor would be called just once when the object is created. 记住,创建对象时,构造函数只会被调用一次。

Moreover there are 2 types of methods instance and static methods. 此外,有两种类型的方法实例和静态方法。 Both types can accept parameters. 两种类型都可以接受参数。 If you are using static parametrized method, then you cannot call the method on the object of the class, since they can operate on static variables of the class. 如果使用静态参数化方法,则无法在类的对象上调用该方法,因为它们可以对类的静态变量进行操作。

Instance parametrized methods can use both instance and static members of the class and they are called on an object. 实例参数化的方法可以同时使用类的实例成员和静态成员,并且它们在对象上被调用。 They represent a machinery to do certain operation on the Object on which you are calling the method upon. 它们代表一种对要在其上调用方法的对象执行某些操作的机制。 The Parameters passed inside these methods ( both static and instance) can act as the input to the operation which you want to accomplish. 这些方法(静态方法和实例方法)内部传递的参数可以用作您要完成的操作的输入。 Unlike constructor which was called only once upon instatantion of the object, You can call the methods as many times as you want. 与仅在对象初始化时调用一次的构造函数不同,您可以根据需要多次调用方法。

Another classic difference is that the constructor always returns the reference to the object. 另一个经典的区别是,构造函数总是将引用返回给对象。 This is the default implicit behavior and we do not need to specify this explicitly in the signature. 这是默认的隐式行为,我们不需要在签名中明确指定此行为。 However method can return anything as per your choice. 但是方法可以根据您的选择返回任何内容。

Example: 例:

public class A {

    String mA;

     /* Constructor initilaizes the instance members */
     public A (String mA) { 
         this.mA = mA;
     } 

     /* this is parameterized method that takes mB as input
        and helps you operate on the object that has the instance
        member mA */

     public String doOperation (String mB) {
         return mA + " " + mB;
     }

     public static void main(String args[]) {

          /* this would call the constructor and initialize the instance variable with "Hello" */
         A a = new A("Hello");

        /* you can call the methods as many times as            you want */
        String b=  a.doOperation ("World");
        String c = a.doOperation ("How are you");

     }
}

Method & Constructor are totally different concept & serves different purpose. 方法和构造函数是完全不同的概念并且服务于不同的目的。

Constructor is specified for initializing your Object and any setting/data set when object creates.You can't call the constructor again & again . 指定构造函数用于初始化对象以及创建对象时的任何设置/数据集。您无法再次调用构造函数。 It will be called once per Object(You may call one constructor from another constructor of that class) 每个对象将调用一次(您可以从该类的另一个构造函数调用一个构造函数)

Method are a functional unit , you can call/reuse them as much as you want. 方法是一个功能单元,您可以随意调用/重用它们。

Hope It was helpful Thanks, 希望对您有所帮助谢谢,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM