构造方法
构造方法是一种特殊的方法
作用:创建对行
格式:
public class 类名{
修饰符 类名(参数){
}
}
功能:主要是完成对象数据的初始化
1.无参构造
package cn.tedu;
public class Student {
private String name;
private int age;
//构造方法
public Student(){
System.out.println("无参构造方法");
}
public void show() {
System.out.println(name+","+age);
}
}
package cn.tedu;
public class StudentDemo {
public static void main(String[] args) {
Student s=new Student();
s.show();
}
}
2.没有定义构造方法时,系统会给出一个默认的无参数构造方法
package cn.tedu;
public class Student {
private String name;
private int age;
public void show() {
System.out.println(name+","+age);
}
}
package cn.tedu;
public class StudentDemo {
public static void main(String[] args) {
Student s=new Student();
s.show();
}
}
3.定义了构造方法时,系统将不在提供无参的构造方法了
package cn.tedu;
public class Student {
private String name;
private int age;
public Student(String name){
this.name=name;
}
public void show() {
System.out.println(name+","+age);
}
}
4.如果定义了带参数的构造方法,还要使用无参的构造方法,就必须再写一个无参的构造方法
推荐使用方法:无论是否使用,都手工写无参数构造方法
方法名相同,参数列表不同
package cn.tedu;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name){
this.name=name;
}
public Student(int age){
this.age=age;
}
public Student(String name,int age){
this.name=name;
this.age=age;
}
public void show() {
System.out.println(name+","+age);
}
}
package cn.tedu;
public class StudentDemo {
public static void main(String[] args) {
Student s1=new Student();
s1.show();
Student s2=new Student("刘");
s2.show();
Student s3=new Student(60);
s3.show();
Student s4=new Student("刘",60);
s4.show();
}
}
标准类制作
package cn.tedu;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public void setAge(int age) {
this.age=age;
}
public int getAge(){
return age;
}
public void show(){
System.out.println(name+","+age);
}
}
package cn.tedu;
public class StudentDemo {
public static void main(String[] args) {
//无参构造方法创建对象后使用setXxx()赋值
Student s1=new Student();
s1.setName("刘");
s1.setAge(30);
s1.show();
//使用带参数构造方法直接闯进啊带属性值的对象
Student s2=new Student("刘",30);
s2.show();
}
}