创建对象的时候默认会调用构造方法来创建对象(在堆中开辟空间),可以完成成员属性的某些初始化操作。
构造方法语法:
public class Teacher {
String name;
int age;
//构造方法
public Teacher(){
System.out.println("调用构造方法");
}
public void teach(){
System.out.println("上课");
}
public static void main(String[] args) {
Teacher teacher = new Teacher();
teacher.name="刘";
teacher.age = 20;
}
}
打印:
调用构造方法
Process finished with exit code 0
注意:
public class Teacher {
String name;
int age;
//构造方法
public Teacher(String namea, int agea){
System.out.println("调用有参构造方法");
name =namea;
age = agea;
}
//无参构造方法
public Teacher(){
System.out.println("调用无参构造方法");
}
public void teach(){
System.out.println("上课");
}
public static void main(String[] args) {
Teacher teacher = new Teacher();
teacher.name="刘";
teacher.age = 20;
System.out.println(teacher.name);
System.out.println(teacher.age);
Teacher teacher2 = new Teacher("张",29);
System.out.println(teacher2.name);
System.out.println(teacher2.age);
}
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。