我刚开始学习Java,来到从Java第九版数量锐减Schildt参数方法和参数的构造函数[第6章]的这个话题,何时使用参数化方法VS参数的构造函数在Java中
我明白了如何声明他们和他们是如何工作的,但我对他们的用法感到困惑,何时使用参数化方法以及何时使用参数化构造函数?
请给我一个简单的比喻的例子。
我刚开始学习Java,来到从Java第九版数量锐减Schildt参数方法和参数的构造函数[第6章]的这个话题,何时使用参数化方法VS参数的构造函数在Java中
我明白了如何声明他们和他们是如何工作的,但我对他们的用法感到困惑,何时使用参数化方法以及何时使用参数化构造函数?
请给我一个简单的比喻的例子。
首先您应该了解构造函数的实际含义。
您可以将“构造函数”看作是每当为类创建对象时都会调用的函数。在类中可以有许多实例变量,即该类的每个对象都有自己的实例变量副本。因此,无论何时使用new ClassName (args)
语句创建新对象,都可以在构造函数中初始化该对象的实例变量的值,因为无论何时您实例化对象时都会首先调用该对象的实例变量值。记住构造函数在创建对象时只会被调用一次。
此外还有2种类型的方法实例和静态方法。两种类型都可以接受参数。如果您使用静态参数化方法,那么您无法在该类的对象上调用该方法,因为它们可以对该类的静态变量进行操作。
实例参数化方法可以使用类的实例和静态成员,并且可以在对象上调用它们。它们代表一种机制来对你调用该方法的对象执行某种操作。在这些方法中传递的参数(包括静态和实例)可以作为您想要完成的操作的输入。 与构造函数在对象的instatantion时只被调用一次不同,您可以根据需要多次调用这些方法。
另一个经典的区别是构造函数总是返回对象的引用。这是默认的隐式行为,我们不需要在签名中明确指定。 然而,方法可以根据您的选择返回任何东西。
实施例:
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");
}
}
他们有一个主要的区别是返回类型。一个构造函数不会返回任何东西,甚至无效。构造函数在类实例化时运行。另一方面,parameterized methods用于类型安全,即允许不需要投射的不同类。
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
}
}
方法&构造是完全不同的概念&供应不同的目的。
构造函数指定用于在创建对象时初始化对象和任何设置/数据集。您不能再次调用构造函数&。它将被每个对象调用一次(您可以从该类的另一个构造函数调用一个构造函数)
方法是一个功能单元,您可以根据需要调用/重用它们。
希望这对我很有帮助 谢谢,
请提供一个示例代码片段作为OP。 OP对此有所了解可能有所帮助。 –
非常感谢, – administr4tor