不积跬步,无以至千里;不积小流,无以成江海。
Java语言基础
Java多态
面向对象程序设计中代码重用的一个重要机制,父类/接口的多种不同实现方式即为多态。
多态的表现形式
- 编译时多态
方法的重载,同一个类中有多个同名方法,当方法的参数不同时,编译时就可以确定调用哪个方法,是同一个类中多态性的表现方式。
- 运行时多态
方法的重写,子类可以重写父类的方法,同样的方法在父类与子类中有着不同的表现形式。父类的引用可以指向子类对象,程序调用的方法在运行期才动态绑定,
多态存在的必要条件
1、要有继承
2、要有重写
3、父类引用指向子类对象
定义一个父类:
class Person { private String name; private int age; int i = 5; public Person(){} public Person(String name, int age){ this.name = name; this.age = age; } public String getname(){ return name; } public void setname(String name){ this.name = name; } public int getage(){ return age; } public void setage(int age){ this.age = age; } public String tostring(){ return "name = " + name + ", age = " + age; } public void eat(){ System.out.println("this is eating!"); } void sleep(){ System.out.println("this is sleeping!"); } }
定义一个子类:
class Student extends Person{ private int score; int i = 10; public Student(){} public Student(String name, int age, int score){ super(name, age); this.score = score; } public int getscore(){ return score; } public void setscore(int score){ this.score = score; } public String tostring(){ return "name = " + getname() + ", age = " + getage() + ", score = " + score; } public void sleep(){ System.out.println("Student's sleeping!"); } public void score(){ System.out.println("Student's score!"); } }
测试:
public class Test{ public static void main(String args[]){ Person p = new Student("tutu", 24, 100); System.out.println(p.i); System.out.println(p.getname()); p.eat(); p.sleep(); // p.score(); Student s = new Student(); System.out.println(s.i); s.score(); System.out.println(p); } }
程序输出:
5 tutu this is eating! Student's sleeping! 10 Student's score! studysuper.Student@15db9742
结论:
多态机制,只针对对象和方法,不针对属性(属性是没有多态性的);
对于方法的多态,子类重写了父类的方法后,在通过对象的向上转型为父类实例化对象时,调用的方法应该是子类重写之后的方法;
子类没有重写,在通过对象的向上转型为父类实例化对象时,调用的是父类的方法。
博客借鉴:https://blog.csdn.net/sunming0129/article/details/79765825