方法与构造器
方法
方法是一段用来完成特定功能的代码片段
方法的定义:
方法包含一个方法头和一个方法体:
修饰符,返回值类型,方法名(与参数表共同构成方法签名·),参数类型,方法体
方法的重载与重写
重载:对于一个方法进行重写修饰符与参数表构成不同的方法
重写:对继承的方法使用其名,但构建不同的方法体。
构造器(Constructor)
构造器–实例化初始值
使用构造器的注意事项:
- 没有返回值
- 必须与类的名称相同
构造器的做用:
- 使用new关键字时必须要有构造器。
- 初始化参数
- 在使用有参构造器时必须显示的定义无参构造器。
使用new关键字时必须要有构造器
Student类
public class Student {
public Student() {
}
public Student(String name) {
this.name = "小欧";
}
public String name;
private String age;
public void study(){
System.out.println(this.name+"在学习");
}
Application类:
public class Application {
public static void main(String[] args) {
Student student = new Student("");
student.study();
}
/**
* Student student = new Student("");
* 第一个Student是Student类,而第二个Student是Student的有参构造器
* 所以我们可以知道 new关键字创建的是构建器中的内容,而接收new类型的是Student类
*/
}
初始化参数
在Student的有参构造器中可以看到将name初始化为了"小欧",无论在Application中给什么值,输出都是:,因为那个(“”)就是申请存储空间的作用,打工人哈哈。
小欧在学习
Process finished with exit code 0
使用有参构造必须要定义无参构造
因为没有无参构造程序是无法识别有参构造的,虽然程序会默认生成一个无参构造,但是我们得知道是必须要有这个无参构造的。