JAVA基础之重载,覆盖/重写,多态
重载发生在同一个类中
特点是两同一不同,类相同,方法名相同,参数不同。其他项与重载无关。
在调用方法的时候,会根据方法名的不同判断具体调用哪个方法。
创建一个Driver类,类中实现了对driver方法的重载操作。
public class Driver { //实现了重载操作 public void drive(){ System.out.println("No Parameter"); } public void drive(String driver){ System.out.println("One Parameter "+driver); } }
测试重载操作
public class Test { public static void main(String[] args){ Driver driver = new Driver(); driver.drive(); driver.drive("Jason"); } }
重写/覆盖
重写和覆盖发生在父类和子类之间,特点是“两同两小一大”,即方法名相同,参数相同,子类返回值类型小或相等,子类抛出异常小或相等,子类方法的访问权限大或相等。
违反这一原则的话,编译会报错。
public class Person { public int a = 10; public void A(){ System.out.println("Person A"); } }
public class Teacher extends Person{ public int a = 20; public void A(){ System.out.println("Teacher A"); } }
public class Test { public static void main(String[] args){ Person person = new Person(); Teacher teacher = new Teacher(); System.out.println("Person A "+person.a); System.out.println("Teacher A "+teacher.a); person.A(); teacher.A(); } }
Person中的变量a和方法A都被其子类覆盖
多态
产生于基类和子类之间
有编译类型和运行类型之分
只有方法有多态,属性没有多态
public class Person { public int a = 10; public void A(){ System.out.println("Person A"); } }
public class Teacher extends Person{ public int a = 20; public void A(){ System.out.println("Teacher A"); } }
public class Test { public static void main(String[] args){ Person person = new Person(); Teacher teacher = new Teacher(); Person p = new Teacher(); System.out.println("Person A "+person.a); System.out.println("Teacher A "+teacher.a); person.A(); teacher.A(); p.A(); System.out.println("Person Teacher A "+p.a); } }
运行结果:
Person A 10
Teacher A 20
Person A
Teacher A
Teacher A
Person Teacher A 10