构造函数用于初始化对象的状态。与方法类似,构造函数还包含在创建对象时执行的语句集合(即指令)。
什么时候构造函数被调用?
每次使用new()关键字创建对象时,都会调用至少一个构造函数(可能是默认构造函数)以将初始值分配给同一类的数据成员。
构造函数在对象或实例创建时被调用。例如:
class Geek
{
.......
// A Constructor
new Geek() {}
.......
}
// We can create an object of above class
// using below statement. This statement
// calls above constructor.
Geek obj = new Geek(); 编写规则构造函数:
Java中有两种类型的构造函数:
// Java Program to illustrate calling a
// no-argument constructor
import java.io.*;
class Geek
{
int num;
String name;
// this would be invoked while object
// of that class created.
Geek()
{
System.out.println("Constructor called");
}
}
class GFG
{
public static void main (String[] args)
{
// this would invoke default constructor.
Geek geek1 = new Geek();
// Default constructor provides the default
// values to the object like 0, null
System.out.println(geek1.name);
System.out.println(geek1.num);
}
}
输出:
Constructor called null 0
// Java Program to illustrate calling of
// parameterized constructor.
import java.io.*;
class Geek
{
// data members of the class.
String name;
int id;
// contructor would initialized data members
// with the values of passed arguments while
// object of that class created.
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
}
class GFG
{
public static void main (String[] args)
{
// this would invoke parameterized constructor.
Geek geek1 = new Geek("adam", 1);
System.out.println("GeekName :" + geek1.name +
" and GeekId :" + geek1.id);
}
}
输出:
GeekName :adam and GeekId :1
在构造函数中没有“返回值”语句,但构造函数返回当前类实例。我们可以在构造函数中写入'return'。
和方法一样,我们可以通过不同的方式重载构造函数来创建对象。编译器根据参数的数量,参数的类型和参数的顺序来区分构造函数。
// Java Program to illustrate constructor overloading
// using same task (addition operation ) for different
// types of arguments.
import java.io.*;
class Geek
{
// constructor with one argument
Geek(String name)
{
System.out.println("Constructor with one " +
"argument - String : " + name);
}
// constructor with two arguments
Geek(String name, int age)
{
System.out.print("Constructor with two arguments : " +
" String and Integer : " + name + " "+ age);
}
// Constructor with one argument but with different
// type than previous..
Geek(long id)
{
System.out.println("Constructor with one argument : " +
"Long : " + id);
}
}
class GFG
{
public static void main(String[] args)
{
// Creating the objects of the class named 'Geek'
// by passing different arguments
// Invoke the constructor with one argument of
// type 'String'.
Geek geek2 = new Geek("Shikhar");
// Invoke the constructor with two arguments
Geek geek3 = new Geek("Dharmesh", 26);
// Invoke the constructor with one argument of
// type 'Long'.
Geek geek4 = new Geek(325614567);
}
}
输出:
Constructor with one argument - String : Shikhar Constructor with two arguments - String and Integer : Dharmesh 26 Constructor with one argument - Long : 325614567
构造函数与Java中的方法有何不同?