构造方法
格式:public 类名称(参数){
方法体
}
功能:完成对象数据的初始化
构造方法可分为无参数与有参数类型
构造方法注意事项:
1.如果没有定义构造方法,系统将会默认给一个无参数的构造方法,如果定义了系统将不在给一个构造方法
2.如果自定义了带参数构造方法,还要使用无参构造方法,就必修再写一个无参构造方法
代码如下:
package demo01;
public class Student {
private String name;
private int age;
public Student() {
System.out.println(“我是无参构造方法”);
}
public Student(String name,int age){
System.out.println(“我是有参构造方法”);
this.name=name;
if(age>=0 && age<=150) {
this.age=age;
}else {
System.out.println(“age 参数不合理”);
}
}
public void setName(String name){
this.name=name;
}
public String getName() {
return this.name;
}
public void setAge(int age) {
this.age=age;
}
public int getAge() {
return this.age;
}
public void show() {
System.out.println("我叫"+this.name+"年龄"+this.age+"岁");
}
}
运行代码:
ackage demo01;
public class demo01Student {
public static void main(String[] args) {
Student stu1=new Student();
stu1.show();
Student stu2=new Student(“迪丽热巴”,30);
stu2.show();
stu2.setAge(31);
stu2.show();
}
}
第二个
package demo02;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name) {
super();
this.name=name;
}
public Student(String name,int age) {
super();
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
运行代码
package demo02;
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name) {
super();
this.name=name;
}
public Student(String name,int age) {
super();
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
运行结果