标签:define 一起学 resolved 参数类型 stat 位置 自己的 参数 new t
不积跬步,无以至千里;不积小流,无以成江海。
Java语言基础
Java方法详述(重载与重写)
重载的概念:
在同一个类中,允许存在一个以上的的同名方法,只要它们的参数个数或者参数类型不同即可。
重载的特点:
与返回值类型无关,只看参数列表,且参数列表必须不同(访问修饰符和返回值类型可以相同也可以不同)。
示例:
public class Test {
	
	public void test(){
        System.out.println("test1");
    }
 
    public void test(int a){
        System.out.println("test2");
    }   
 
    //以下两个参数类型顺序不同
    public void test(int a,String s){
        System.out.println("test3");
    }   
 
    public void test(String s,int a){
        System.out.println("test4");
    }   
 
    public static void main(String[] args){
        Test o = new Test();
        o.test();
        o.test(1);
        o.test(1,"test3");
        o.test("test4",1);
    }
}
运行结果:
test1 test2 test3 test4
重写的概念:
重写是子类重写父类允许访问的方法。返回值和参数类型必须相同。(存在于子类和父类中)
重写的好处在于子类可以根据需要,定义特定于自己的行为。 也就是说子类能够根据需要实现父类的方法。
示例:
class Animal{	
	public void move(){
		System.out.println("动物可以移动");
	}
}
 
class Dog extends Animal{
	public void move(){
		System.out.println("狗可以跑和走");
	}
}
 
public class TestDog{
	public static void main(String args[]){
	   Animal a = new Animal(); // Animal 对象
	   Animal b = new Dog(); // Dog 对象
 
	   a.move();// 执行 Animal 类的方法
	   b.move();//执行 Dog 类的方法
	}
}
运行结果:
动物可以移动 狗可以跑和走
注意一个错误:
class Animal{	
	public void move(){
		System.out.println("动物可以移动");
	}
}
 
class Dog extends Animal{
	public void move(){
		System.out.println("狗可以跑和走");
	}
	public void bark(){
	      System.out.println("狗可以吠叫");
	   }
}
 
public class TestDog{
	public static void main(String args[]){
	   Animal a = new Animal(); // Animal 对象
	   Animal b = new Dog(); // Dog 对象
 
	   a.move();// 执行 Animal 类的方法
	   b.move();//执行 Dog 类的方法
	   b.bark();
	}
}
运行结果:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method bark() is undefined for the type Animal at TestDog.main(TestDog.java:24)
原因:b的引用类型Animal没有bark方法。
需要这么改:
class Animal{	
	public void move(){
		System.out.println("动物可以移动");
	}
}
 
class Dog extends Animal{
	public void move(){
		System.out.println("狗可以跑和走");
	}
	public void bark(){
	      System.out.println("狗可以吠叫");
	   }
}
 
public class TestDog{
	public static void main(String args[]){
	   Animal a = new Animal(); // Animal 对象
	   Dog b = new Dog(); // Dog 对象
 
	   a.move();// 执行 Animal 类的方法
	   b.move();//执行 Dog 类的方法
	   b.bark();
	}
}
运行结果:
动物可以移动 狗可以跑和走 狗可以吠叫
重载和重写对比:
| 重写 | 重载 | |
| 位置 | 父子类、接口与实现类 | 本类 | 
| 方法名称 | 一致 | 一致 | 
| 参数列表 | 不能修改 | 必须修改 | 
| 返回类型 | 不能修改 | 可以修改 | 
| 异常 | 不能扩展 | 可以修改 | 
标签:define 一起学 resolved 参数类型 stat 位置 自己的 参数 new t
原文地址:https://www.cnblogs.com/smilexuezi/p/11898663.html