public int getAge(){
return age;
}
public void study(){
System.out.println("学习");
}
public void doHomeword(){
System.out.println("做作业");
}
}
package STUDENT;
public class StudentCase {
public static void main(String[] args) {
Student s = new Student();
s.name = "小明";
s.setAge(30);
s.study();
s.doHomeword();
System.out.println(s.name);
System.out.println(s.getAge());
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/d11465d96afb44c0a7835a6c72454221.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl81MTE0NjMyOQ==,size_16,color_FFFFFF,t_70)
### [](https://docs.qq.com/doc/DSmxTbFJ1cmN1R2dB)注意事项
1. **构造方法的创建** (构造快捷键Alt + insert)
如果没有定义构造方法,系统将会给出一个默认的无参数构造方法
如果定义了构造方法,那么系统将不再提供默认的构造方法
2. **构造方法的重载**
如果自定义了带参构造方法,还要使用午餐构造方法,那么必须再写一个无参构造方法
3. **推荐使用的构造方法**
`无论是否使用,都手工书写无参数构造方法`
#### [](https://docs.qq.com/doc/DSmxTbFJ1cmN1R2dB)演示各种构造方法
package STUDENT;
public class Student {
String name;
private int age;
//无参构造方法
public Student(){
System.out.println("无参数构造方法");
}
//带一个参数的构造方法
public Student(String name){
this.name = name;
}
public Student(int age){
this.age = age;
}
//带两个参数的构造方法
public Student(String name, int age){
this.age = age;
this.name = name;
}
public void setAge(int a){
if (a < 0) System.out.println("年龄输入有误");
else age = a;
}
public int getAge(){
return age;
}
public void study(){
System.out.println("学习");
}
public void doHomeword(){
System.out.println("做作业");
}
}
package STUDENT;
public class StudentCase {
public static void main(String[] args) {
//无参数
Student s1 = new Student();
System.out.println(s1.name);
System.out.println(s1.getAge());
System.out.println("-----------------------------------");
//一个参数
Student s2 = new Student("小明");
System.out.println(s2.name);
System.out.println(s2.getAge());
System.out.println("-----------------------------------");
Student s3 = new Student(13);
System.out.println(s3.name);
System.out.println(s3.getAge());
System.out.println("-----------------------------------");
//两个参数
Student s4 = new Student("小明", 13);
System.out.println(s4.name);
System.out.println(s4.getAge());
}