一个方法的组成:
- 方法头: 包括方法的修饰符、返回值类型、方法名、形式参数(最后两项是方法签名)
- 方法体: 在Java语言中方法体一个方法中用大括号{}括起来的部分
方法签名: 方法名称+参数列表(包括参数的类型和顺序)
注意,签名不包括方法的访问修饰符合返回类型
应用场景-重载和重写:
- 重载(Override): 一个类中,定义的多个参数名相同但是参数列表不同的方法(签名不同)
- 重写(Overlode): 子父类中,子类定义的和其从父类继承而来的方法中方法签名完全相同的方法。
注意:必须是从父类继承而来的方法。父类中的private方法,子类没有权限继承,因而重写不了。
拿一个方法的例子进行分析
private static int getNumber(String name, int age, double weight) {
return new Random().nextInt(99);
}
上述方法中:
方法头: private(修饰符), static(修饰符), int(返回值), getNumber(方法名字), 形式参数(String, int, double)
方法体: {return new Random().nextInt(99);}
方法签名: getNumber(方法名字), 形式参数(String, int, double)及形式参数的顺序
关于方法签名的原文:
The method header specifies the modifiers, return value type, method name, and parameters of the method. The static modifier is used for all the methods in this chapter. The reason for using it will be discussed in Chapter 8, Objects and Classes.
The variables defined in the method header are known as formal parameters or simply parameters. A parameter is like a placeholder: when a method is invoked, you pass a value to the parameter. This value is referred to as an actual parameter or argument. The parameter list refers to the method’s (???) type, order, and number of the parameters. The method name and the parameter list together constitute the method signature. Parameters are optional; that is, a method may contain no parameters. For example, the Math.random() method has no parameters
[1] Introduction to Java Programming 10th. 6.2 Defining a Method