Java 多态
多态性的体现:
方法的重载和重写;
对象的多态性
对象的多态性:
向上转型:程序会自动完成
格式:父类 父类对象 = 子类实例
向下转型:强制类型转换,需要先向上转型再向下转型
格式:子类 子类对象 = (子类)父类实例
例1:向上转型
package com.jike.duotai; class A{ public void tell1() { System.out.println("A-tell 1"); } public void tell2() { System.out.println("A-tell 2"); } } class B extends A{ public void tell1(){ System.out.println("B-tell 1"); } public void tell3() { System.out.println("B-tell 3"); } } public class test01 { public static void main(String[] args) { // 向上转型 B b=new B(); A a =b; a.tell1(); a.tell2(); } }
输出:
B-tell 1 A-tell 2
因为a是子类实例b转化来的,所以执行的B中重写的方法tell1。
其中:
B b=new B(); A a =b;
可以写成:
A a=new B();
例2:向下转型,需要先向上转型才能完成。
package com.jike.duotai; class A{ public void tell1() { System.out.println("A-tell 1"); } public void tell2() { System.out.println("A-tell 2"); } } class B extends A{ public void tell1(){ System.out.println("B-tell 1"); } public void tell3() { System.out.println("B-tell 3"); } } public class test01 { public static void main(String[] args) { A a=new B(); //先向上转型 B b=(B)a; b.tell1(); b.tell2(); b.tell3(); } }
输出:
B-tell 1 A-tell 2 B-tell 3
tell1执行的仍然是子类中的。
多态的应用:可以使不同子类中同样名称的方法完成不同的功能。
package com.jike.duotai; abstract class Person{ private int age; private String name; public Person(int age,String name) { this.age=age; this.name=name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public abstract void want(); } class Student extends Person{ private int score; public int getScore() { return score; } public void setScore(int score) { this.score = score; } public Student(int age, String name,int score) { super(age, name); this.score=score; } public void want() { System.out.println("姓名:"+getName()+" 年龄:"+getAge()+" 成绩:"+getScore()); } } class Worker extends Person{ private int money; public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } public Worker(int age, String name,int money) { super(age, name); this.money=money; } public void want() { System.out.println("姓名:"+getName()+" 年龄:"+getAge()+" 工资:"+getMoney()); } } public class test03 { public static void main(String[] args) { Student student=new Student(10, "小明", 100); student.want(); Worker w=new Worker(30, "老明", 1000); w.want(); } }
输出:
姓名:小明 年龄:10 成绩:100 姓名:老明 年龄:30 工资:1000