JAVA 构造函数及其重载

public class Student{
public int stuId;
public String stuName;
public int stuAge;
public int stuScore;
public Student(){
}
public Student(int sId,String sName){
stuId = sId;
sName = stuName;
}

public Student(int sld,Sting sName,int sAge,int sScor){
			stuId = sId;
			sName = stuName;
			sAge = stuAge;
			sScore = stuScore;
}

}

注意:
1、对于构造方法而言 不能有返回值也不能用void对其进行定义
2、名称必须与当前类名相同 ,但是可以重载(参数不同 (类型与个数不同))
3、构造方法只有由系统在创建当前类时自动调用,不可由main函数中定义此类的对象进行调用
4、需要那种初始化(哪种构造就用哪种构造建立对象,开辟空间)
e.g. 1、Student stu1 = new Student();
2、Student stu2 = new Student(201010110,“哈呵哈呵”);
3、Student stu3 = new Student(1021222,“哈呵哈呵”,20,100);
以上给出了不同构造函数的重载,不同构造的同一个类的实例化对象,在实例化对象时系统就会自动调用构造函数,给相应得值进行初始化赋值;不同的构造进行不同得初始化,不同的赋值
5、如果类中没有定义构造函数,系统会在实例化对象时创建一个构造函数;但如果此类中有任何构造函数则系统不会创建任何得构造函数
系统创建的构造函数为 :
public 类名(){
}

猜你喜欢

转载自blog.csdn.net/weixin_44895008/article/details/89290956