1、我们想通过构造方法将外部传入的参数赋值给类的成员变量,构造方法的形式参数名称与类的成员变量名相同。例如:
class Person{
String name;
public Person(String name){
this.name = name;
}
}
2、假设有一个容器类和一个部件类,在容器类的某个方法中要创建部件类的实例对象,而部件类的构造方法要接受一个代表其所在容器的参数。例如:
class Container{
Component comp;
public void addComponent(){
comp = new Component(this);
}
}
class Component{
Container myContainer;
public Component(Container c){
myContainer = c;
}
}
3、构造方法是在产生对象时被java系统自动调用的,我们不能再程序中像调用其他方法一样去调用构造方法。但我们可以在一个构造方法里调用其他重载的构造方法,不是用构造方法名,而是用this(参数列表)的形式,根据其中的参数列表,选择相应的构造方法。例如
public class Person{
String name;
int age;
public Person(String name){
this.name = name;
}
public Person(String name,int age){
this(name);
this.age = age;
}
}