2019-05-26 java学习日记

面向对象多态的概述及其代码体现

多态(polymorphic):事物存在的多种形态

多态前提

1,要有继承关系。
2,要有方法重写。
3,要有父类引用指向子类对象。

例子

class Demo1_Polymorphic {
  public static void main(String[] args) {
    Cat c = new Cat(); c.eat();

    Animal a = new Cat(); //父类引用指向子类对象
     a.eat();}

}

class Animal {
  public void eat() {
    System.out.println("动物吃饭");}}

class Cat extends Animal {
  public void eat() {
    System.out.println("猫吃鱼"); }}

 

 

多态中的成员访问特点:

成员变量

编译看左边(父类),运行看左边(父类)

成员方法

编译看左边(父类),运行看右边(子类)。
这叫做动态绑定,编译看父类有没有这个方法,运行是运行子类的。

静态方法

编译看左边(父类),运行看左边(父类)。
(静态和类相关,算不上重写,所以,访问还是左边的)
只有非静态的成员方法,编译看左边,运行看右边 (是通过类名点去调用的)

例子

class Demo2_Polymorphic {
  public static void main(String[] args) {

   /*Father f = new Son(); //父类引用指向子类对象

  System.out.println(f.num);

  Son s = new Son();
  System.out.println(s.num);*/

  Father f = new Son();
  //f.print();
  f.method(); //相当Father.method()
  }

}

class Father { i

  nt num = 10;

public void print() {

   System.out.println("father"); }


public static void method() {
  System.out.println("father static method");
}

}

class Son extends Father { int num = 20;


public void print() {

   System.out.println("son");}

public static void method() {

   System.out.println("son static method");}

}

 

 

多态中向上转型和向下转型

基本数据类型自动类型提升和强制类型转换,如:

int i = 10;

byte b = 20;

//i = b; //自动类型提升

//b = (byte)i; //强制类型转换

多态中向上转型和向下转型如:

Person p = new SuperMan(); //父类引用指向子类对象,超人提升为了人

//父类引用指向子类对象就是向上转型

  System.out.println(p.name);

  p.谈生意();

  SuperMan sm = (SuperMan)p; //向下转型

  sm.fly();

 

注:在主方法里写方法要加个静态

 

 

 

多态的好处与弊端

多态的好处

1,提高了代码的维护性(继承保证)
2,提高了代码的扩展性(由多态保证)
3,可以当作形式参数 ,可以接收任意子类对象

多态的弊端

1,不能使用子类特有属性和行为

 

关键字 :instanceof

判断前边的引用是否是后边的数据类型

如:

public static void method(Animal a) {
  if (a instanceof Cat) {
    Cat c = (Cat)a;
    c.eat();
    c.CatchMouse();
  }else (a instanceof Dog) {
    Dog d = (Dog)a;
    d.eat();
    d.lookhome();
  }else { a.eat; }}}

 

 

 1 class Demo_Polymorphic {
 2     public static void main(String[] args) {
 3         A a = new A();
 4         a.show();
 5         B b = new B();
 6         b.show();
 7         C c = new C();
 8         c.show();
 9         D d = new D();
10         d.show();
11     }
12 }
13 class A {
14     public void show (){
15         show2();
16     }
17     public void show2 (){
18         System.out.print("天");
19     }
20     
21 }
22 class B extends A{
23     public void show2 (){
24         System.out.print("河");
25     }
26 }
27 class C extends B{
28     public void show2 (){
29         System.out.print("先");
30     }
31 }
32 class D extends C{
33     public void show (){
34         super.show();
35     }    
36     public void show2 (){
37         System.out.println("生");
38     }
39 }
例子分析题

 

posted @ 2019-05-26 23:00  白河ia  阅读(197)  评论(0编辑  收藏  举报