Java类的构造方法(constructor):
1.构造函数名与类名相同
2.构造函数不返回任何值,也没有返回类型(包括void)
3.每一个类可以有一个或多个构造方法;
4.构造方法在创建对象时自动执行,不用显式地直接调用。
实现形式:
1.系统默认的构造方法。
2.自定义构造方法与方法重载
3.自定义无参的构造方法
4.this
public class Person {
private String name;
private int age;
public Person(){
System.out.println("this is a default constructor!");
} //default constructor
public Person(String s)
{
name = s;// or using the key word -- this.
//this.name = s;
System.out.println("this is a default constructor with one parameter!");
}
public Person(String s, int n){
//name = s;
this.name = s;
//age = n;
this.age = n;
System.out.println("this is a default constructor with two parameter!");
}
public String talk(){
return "My name is "+name+", and age is "+age+".";
}
}
public class TestConstruct
{
public static void main(String[] args)
{
Person p1 = new Person();
Person p3 = new Person("jiaojiao");
Person p2 = new Person("Wenliang", 25);
System.out.println(p1.talk());
System.out.println(p2.talk());
System.out.println(p3.talk());
}
}