java隨手筆記三之多態,java多態

來源:互聯網
上載者:User

java隨手筆記三之多態,java多態
多態:---一個對象的多種形態實質:父類的引用指向子類對象---前提:必須有繼承或者是實現class Animal{}class Dog extends Animal{}main{Dog d = new Dog(); //本態Animal dog = new Dog(); //多態} 注意:通過多態形式建立的對象,只能訪問子父類共有的成員方法,運行結果為子類結果是子類特有的成員方法不能方法。虛擬方法調用:父類對象調用子類特有的方法Student S = new Student("張三",100);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, 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;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.