多態:
---一個物件的多種形態
實質:父類別的引用指向子類別物件
---前提:必須有繼承或是實作
class Animal{}
class Dog Dog extends Animal{}
main{
Dog d = new Dog(); //本態
Animal dog = new Dog(); //多態性
}
的對象,只能存取子父類別共有的成員方法,運行結果為子類別結果是子類別特有的成員方法不能方法。 虛擬方法呼叫:父類別物件呼叫子類別特有的方法Student S = new Student("張三",100);Person p = new Student("李四",200);Person p = new Student("李四",200);
System.out.println(S.say());
System.out.println(p.say());
多態性數組— 在引用類型的陣列中,使用多態性形式來存放物件。
eg:Person[] person = {new Person("張三", 32),
new Student("李四", 21, 120, 90.0),
new Student("王五", 22,五", 22, 119, 91.5),
new Teacher("劉老師", 35, 10, "Java EE"),
new Teacher("張老師", 11)};
中的參考型別參數instanceof運算子— 判斷一個物件是否為指定型別(形態)強制型別轉換— 將物件從一種參考型態轉換為另一種參考型態物件關聯:一個物件中使用了另一個物件一對一,一對多,多對一class test4 { public static void main(String[] args){ Person p = new Person("王五",50); method(p); Student S = new Student("张三",100); method(S); Person p1 = new Student("赵四",100); method(p1); } public static void method(Person p){ if (p instanceof Student){ System.out.println("教师"); Student s = (Student)p; System.out.println("本态方法调用:"+p.say()); }else{ System.out.println("人"); } System.out.println(p.say()); } } class Person{ private String name; private int age; public Person(){} public Person(String name,int age){ this.name = name; this.age = age; } public String getName(){ return name; } public String say(){ return "姓名:"+name+"年龄:"+age; } } class Student extends Person{ private int id; private double score; public Student(String name,int id){ this(name,20,id,98.5); } public Student(String name,int age,int id,double score){ super(name,age); this.id = id; this.score = score; } public double getId(){ return id; } public String say(){ return super.say()+"学号:"+id+"分数:"+score; } }