1.方法重载与方法重写
方法重载overload和方法重写override实质上没有任何关系;overload是在同一个类中进行改写,override是子类对父类的改写,实在是没有什么好混淆的
1.方法重载
方法重载overload指的是在同一个类中,方法名必须一致,方法体参数被修改:a.参数值个数不同;b.参数值类型被修改;比如int a改为double a;c.方法中参数值调换位置;
1、同一个类中
2、方法名相同,参数列表不同(参数顺序、个数、类型)
3、方法返回值、访问修饰符任意
4、与方法的参数名无关
譬如:
public static boolean isEventNumber(int number) {
if (number % 2 == 0) {
return true;
} else {
return false;
}
}
public static boolean isEventNumber(int number,String s) {
if (number % 2 == 0) {
return true;
} else {
return false;
}
}
2. 方法重写
方法重写override是在不同的类中,子类对父类表示不满,要对父类的方法进行重写的方式;
1、有继承关系的子类中
2、方法名相同,参数列表相同(参数顺序、个数、类型),方法返回值相同
3、访问修饰符,访问范围需要大于等于父类的访问范围
4、与方法的参数名无关
class Animal{
public void move(){
System.out.println("动物可以移动");
}
}
class Dog extends Animal{
public void move(){
super.move(); // 应用super类的方法
System.out.println("狗可以跑和走");
}
}
public class TestDog{
public static void main(String args[]){
Animal b = new Dog(); // Dog 对象
b.move(); //执行 Dog类的方法
}
}
//以上实例编译运行结果如下:
动物可以移动
狗可以跑和走
3.用表格来区分
* | 英文 | 位置 | 修饰符 | 返回值 | 方法名 | 参数 | 抛出异常 | 方法体 |
---|---|---|---|---|---|---|---|---|
重载 | overload | 同一个类中 | 无关 | 无关 | 必须相同 | 必须不同 | 无关 | 不同 |
重写 | override | 子类 父类中 | 父类的权限修饰符要低于子类的 | 父类的返回值类型大于子类 | 必须相同 | 必须相同 | 小于等于 | 不同 |
4.访问修饰符
修饰符 | 类内部 | 同一个包 | 子类 | 任何地方 |
---|---|---|---|---|
private | yes | |||
default | yes | yes | ||
protected | yes | yes | yes | |
public | yes | yes | yes | yes |
对于class的权限修饰符只可以用public和default
a.public类可以在任意地方被访问
b.default只可以被同一个包内部的类访问
5.写方法
写方法应注意两个明确:
1.返回值类型
2.参数
譬如:
查找数组索引,代码如下
package com.max;
import java.util.Scanner;
public class max {
public static void main(String[] args) {
int[] arr = {23,5,634,2424,232};
Scanner sc = new Scanner(System.in);
System.out.println("please enter your number: ");
int number = sc.nextInt();
int index = getIndex(arr,number);
/**
int index = -1;
for (int i =0;i<arr.length;i++){
if (arr[i]==number){
index = i;
break;
}
}
*/
System.out.println("index:"+index);
}
public static int getIndex(int[] arr,int number){
int index = -1;
for (int i =0;i<arr.length;i++){
if (arr[i]==number){
index = i;
break;
}
}
return index;
}