【Java 基础篇】【第五课】类的构造函数

时间:2024-01-01 13:40:39

Java 也有自己的构造函数,如同c++一样有两个特征:

1.构造函数的名字和类的名字相同

2.构造函数没有返回值

下面来看一下这个例子:

 public class test
{
public static void main(String[] args)
{
Human aman = new Human(20);
}
} class Human
{
// constructor
// 然后再进行构造初始化
Human(int h)
{
System.out.println("construct height is " + height);
this.height = h;
System.out.println("construct height is " + height);
} // 首先初始化这里
private int height = 10;
}

输出 是这样的:

construct  height is 10
construct  height is 20

根据上面的代码,可以得出:

构建方法 > 显式初始值 > 默认初始值

重载:

当然一个类可以有多个构造函数,就像C++一样

 public class test
{
public static void main(String[] args)
{
Human aman = new Human(20);
Human bman = new Human(60, "hello");
}
} class Human
{
// constructor 1
Human(int h)
{
System.out.println("construct 1 " + h);
} // constructor 2
Human(int h, String str)
{
System.out.println("construct 2 " + h + " " + str );
}
}

输出结果:
construct 1 20
construct 2 60 hello

当然不止构造函数可以重载,只要是类的函数就都可以重载

应该很好理解吧 ~~