Java 也有本身的构造函数,如同c++同样有两个特征:java
1.构造函数的名字和类的名字相同c++
2.构造函数没有返回值ide
下面来看一下这个例子:函数
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; }
输出 是这样的:this
construct height is 10
construct height is 20spa
根据上面的代码,能够得出:orm
构建方法 > 显式初始值 > 默认初始值ci
重载:it
固然一个类能够有多个构造函数,就像C++同样form
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
固然不止构造函数能够重载,只要是类的函数就均可以重载
应该很好理解吧 ~~