我的总结2《构造方法》
1•方法的分类:普通方法和构造方法
2•构造方法作用:用来实例化对象和初始化属性值
3•格式
public 类名(数据类型 参数名,...){
}
构造方法不需要定义返回值类型
4•Java会给没一个类都提供一个默认的构造方法。
但是如果自定义了构造方法,则默认的构造方法将被覆盖,无法再继续使用。
如果还需要使用默认的构造方法,应该把默认的写出来。
5•方法重载
1•注意:方法重载是在一个类中
2•构造方法和普通方法都可以使用方法的重载。
3.重载的要求:1.方法名必须要完全相同;
2.方法所带的参数个数,参数类型,参数顺序必须要有一个不同。
4.使用:根据参数不同来调用不同的重载方法。
6•this关键字
1.用途
1.当参数名和属性名完全相同的时候,使用this来区分属性和参数,加上this的表示属性,没有加的则是参数。
2.this关键字是可以用来调用构造方法的,但是要带上对应的数据类型值,达到在一个构造函数中调用另一个构造函数的目的。(参见Test0)
2.表示的对象
this表示的是当前调用方法的对象。
实验代码:模拟学生学习
public class Student {
String name;//姓名属性
double score;//学分属性
//定义构造方法,其中this指向第三次的
public Student(String name){
this(name,5);
}
//重载构造方法,其中this指向第一次的
public Student(){
this("未命名");
}
public Student(String name,int score){
this.name = name;
this.score = score;
}
//定义设置姓名属性值的方法
public void setName(String name){
this.name = name;
}
//定义获取姓名属性值的方法
public String getName(){
return name;
}
//定义学习的方法
public void study(){
score++;
System.out.println(name+"学习中,学分是"+score);
}
//重载学习方法
public void study(int score){
this.score += score;
System.out.println(name+"学习中,学分是"+this.score);
}
}
public class Test {
//程序的入口主函数
public static void main(String [] args){
//实例化一个Student类的对象
Student stu = new Student("李四");
stu.study();
Student stu2 = new Student();
stu2.study(5);
}
}
1•方法的分类:普通方法和构造方法
2•构造方法作用:用来实例化对象和初始化属性值
3•格式
public 类名(数据类型 参数名,...){
}
构造方法不需要定义返回值类型
4•Java会给没一个类都提供一个默认的构造方法。
但是如果自定义了构造方法,则默认的构造方法将被覆盖,无法再继续使用。
如果还需要使用默认的构造方法,应该把默认的写出来。
5•方法重载
1•注意:方法重载是在一个类中
2•构造方法和普通方法都可以使用方法的重载。
3.重载的要求:1.方法名必须要完全相同;
2.方法所带的参数个数,参数类型,参数顺序必须要有一个不同。
4.使用:根据参数不同来调用不同的重载方法。
6•this关键字
1.用途
1.当参数名和属性名完全相同的时候,使用this来区分属性和参数,加上this的表示属性,没有加的则是参数。
2.this关键字是可以用来调用构造方法的,但是要带上对应的数据类型值,达到在一个构造函数中调用另一个构造函数的目的。(参见Test0)
2.表示的对象
this表示的是当前调用方法的对象。
实验代码:模拟学生学习
public class Student {
String name;//姓名属性
double score;//学分属性
//定义构造方法,其中this指向第三次的
public Student(String name){
this(name,5);
}
//重载构造方法,其中this指向第一次的
public Student(){
this("未命名");
}
public Student(String name,int score){
this.name = name;
this.score = score;
}
//定义设置姓名属性值的方法
public void setName(String name){
this.name = name;
}
//定义获取姓名属性值的方法
public String getName(){
return name;
}
//定义学习的方法
public void study(){
score++;
System.out.println(name+"学习中,学分是"+score);
}
//重载学习方法
public void study(int score){
this.score += score;
System.out.println(name+"学习中,学分是"+this.score);
}
}
public class Test {
//程序的入口主函数
public static void main(String [] args){
//实例化一个Student类的对象
Student stu = new Student("李四");
stu.study();
Student stu2 = new Student();
stu2.study(5);
}
}