Java入门学习笔记-构造体

197 阅读1分钟

首先举一个简单包含构造体的类:

public class Test
{
    public String name;
    public int num;
    public Test(String name , int num)
    {
        this.name = name;
        this.num = num;
    }
    public static void main(String[] args)
    {
        Test person = new Test("路人甲",20);
        System.out.println("姓名:"+person.name);
        System.out.println("学号:"+person.num);
    }
}

通常建议为Java类保留无参数的默认构造体。因此,如果为一个类编写了有参数的构造体,通常建议为该类额外编写一个无参数的构造体。

构造器重载与方法重载基本相同,需要注意的是构造器必须与类名相同,且同一个类内所有的构造器都得相同。为了能让系统区别不同的构造器,多个构造器的参数列表必须不同。

public class Test
{
    public String name;
    public int num;
    public Test()
    {
    }
    public Test(String name , int num)
    {
        this.name = name;
        this.num = num;
    }
    public static void main(String[] args)
    {
        Test person = new Test("路人甲",20);
        Test person = new Test("路人甲",20);
        System.out.println("姓名:"+person.name);
        System.out.println("学号:"+person.num);
    }
}

上述的Test类提供了2个重载的构造体,两个构造体名字相同,形参不同,系统便会根据不同的形参决定调用哪个构造器。

当我们遇到多个构造器内包含相同的内容,但又不完全一致。假设一个构造器Test有A、B两个形参,另一个Test构造器有A、B、C三个形参,我们便可以运用this在一个构造器中调用另一个构造器。

public class Test
{
    public int A;
    public int B;
    public int C;
    public Test(int A,int B)
    {
        this.A = A;
        this.B = B;
    }
    public Test(int A,int B,int C)
    {
        this(A , B);//包含了上个Test构造器中的A和B,但还需要C
        this.C = C;
    }
    public static void main(String[] args)
    {
        Test person = new Test(12,20,30);
        System.out.println("A:"+person.A);
        System.out.println("B:"+person.B);
    }
}