Java程序设计—面向对象0120

Posted on 2018-01-21 12:08  Jonathan_C  阅读(112)  评论(0)    收藏  举报
  • 多态的思想:

    1. 对象的类型具有两种:一种为编译类型(声明对象变量的类型),另一种是运行类型(对象的真实类型)。

 1 class Animal{
 2     public void eat() {
 3         System.out.println("Eat food");
 4     }
 5 }
 6 class Dog extends Animal{
 7     public void eat() {
 8         System.out.println("Eat dog food");
 9     }
10 }
11 
12 public class J2_OOP_Polymorphic {
13     public static void main(String[] args) {
14         Animal obj=new Dog();//编译类型为animal,运行类型为Dog()
15     }
16 }

    2. 当编译类型和运行类型不同的时候,多态就出现了。编译类型必须是运行类型的父类。

    3. 所谓多态,指对象可以有不同的形态,拥有多种形式。

    4. 多态可以是:类与类的关系,更多的是:接口和实现类的关系。

    5. 多态的出现是当子类对象运行的时候,表现出自身的特征。

  • 多态的好处:屏蔽不同子类之间的差异,达到通用编程。例如下面的代码,通过创建animal子父类体系,当feeder需要喂不同的animal子类的时候,将形参设为父类,当任意子类调用时,自动调用该子类。
 1 class Animal{
 2     private String name;
 3     Animal(String name){
 4         this.name=name;
 5     }
 6     public void eat() {
 7         System.out.println("Eat food");
 8     }
 9     public String showName() {
10         return this.name;
11     }
12 
13 }
14 
15 class Dog extends Animal{
16     Dog(String name){
17         super(name);
18     }
19     public void eat() {
20         System.out.println("Eat dog food");
21     }
22 }
23 
24 class Cat extends Animal{
25     private String name;//not used
26 //    Cat(String name){
27 //        this.name=name;
28 //    }//exception!!!
29     Cat(String name){
30         super(name);
31     }
32     public void eat() {
33         System.out.println("Eat cat food");
34     }
35     
36 }
37 class feeder{
38     public void feed(Animal a) {//Animal a will automatically convert into its subclass object while calling this method.
39         System.out.println("feed food to "+a.showName());
40         a.eat();
41     }
42 }
43 public class J2_OOP_Polymorphic {
44     public static void main(String[] args) {
45         Animal d=new Dog("Dog");
46         Animal c=new Cat("Cat");
47         feeder f=new feeder();
48         f.feed(d);
49         f.feed(c);
50     }
51 }
  • 基本数据类型转换
    • 显示(强制):大类型的数据赋值给小类型的数据。 e.g. short s=10; int i=s;//exception!!!损失精度。强转 int i=(short) s;
    • 隐式(自动):小类型的数据赋值给大类型的数据 e.g. byte B=12; int i=B.
  •  引用类型的转换:大和小是父类与子类的关系
    • 显示(强制):
1 class Animal{
2 }   
3 class Cat extends Animal{
4 }
5 //main中
6 
7 Animal a=new Cat();
8 Cat c=a;//无法转,需要强制转
9 Cat c=(Cat) a;
    • 有时候强制转换,可以结合instanceof运算符来完成。如下,父类子类声明略过。
 1 class feeder{
 2     public void feed(Animal a) {//Animal a will automatically convert into its subclass object while calling this method.
 3         System.out.println("feed food to "+a.showName());
 4         a.eat();
 5         if(a instanceof Dog) {
 6             ((Dog) a).bark();//强制转换,将a转成Dog类
 7         }
 8         else if(a instanceof Cat) {
 9             ((Cat) a).playBall();//强制转换,将a转成Cat类
10         }
11     }
12 }
    • 隐式(自动):多态的转换,子类的对象赋值给父类变量。
1 class Animal{
2 }   
3 class Cat extends Animal{
4 }
5 //main中
6 
7 Animal a=new Cat();
  • 总体来说,继承会破坏封装,因为子类可以修改父类的信息。