ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Java基础 |(六)构造函数/方法(constructor)

Java基础 |(六)构造函数/方法(constructor) 构造函数/方法(constructor)参考Java构造器构造方法 -Java教程1.作用用于初始化对象一种特殊的方法__构造方法 对象的出生仪式__。 孩子一出生就要哭、要登记户口。new一个对象时构造方法就要执行——把字段初始化、注册到系统、做准备工作。2.为什么叫“构造”函数在对象创建时调用它它来提供对象的数据即构造值因此叫构造函数3.规则|规定构造函数名必须与其类名相同构造函数必须没有显式返回类型4.构造函数类型无参数构造函数默认构造函数default constructor参数化构造函数 有参数parameterized constructor4.1.无参数构造函数默认构造函数class_name(){}public class bicycle { bicycle(){ System.out.println(对象b被创建); } //构造函数在创建对象时被调用 public static void main(String[] args) { bicycle b new bicycle(); } } //运行结果对象b被创建如果类中没有构造函数编译器会自动创建一个默认构造函数。默认构造函数根据类型为对象提供默认值如0null等public class Student { //属性 int id; String name; //方法 void display(){ System.out.println(id name); } public static void main(String[] args) { //创建对象s1,s2 Student s1 new Student(); Student s2 new Student(); //调用 s1.display(); s2.display(); } }//运行结果 0 null 0 null Process finished with exit code 0在上面的类中代码中并没有创建任何构造函数但编译器自动提供了一个默认构造函数。默认构造函数分别为字段id和name分别提供了0和null值4.2.参数化构造函数有参数作用为不同对象提供不同初始化的值public class Student { int id; String name; void display(){ System.out.println(id name); } //参数化构造函数 Student(int i,String n){ id i; name n; } public static void main(String[] args) { //创建对象s1,s2 Student s1 new Student(123,张三); Student s2 new Student(456,李四); s1.display(); s2.display(); } }//运行结果 123 张三 456 李四 Process finished with exit code 0
返回列表