java中的多态和接口
对象上下转型
1由子类转型成父类,在继承图上是向上移动的,一般称为向上转型
2向上转型是重一个专用类型向较通用的类型转换,所以总是安全的
3向上转型过程中,类接口中唯一可能发生的事是丢失方法,反而不是获得方法
4与会相反的操作是向下转型,不安全(需要instanceof操作符协)
1 public class AnimalDemo{ 2 public static void main(String []args){ 3 Animal aa = new Dog("旺财");//向上转型 4 aa.eat(); 5 aa.sleep(); 6 Animal bb = new Cat("招财猫"); 7 bb.eat(); 8 bb.sleep(); 9 //向下转型是不安全的 10 if(aa instanceof Cat){ 11 System.out.println("aa");//判断是否可以转可以的话就会打印aa 12 Cat cat = (Cat)aa;//将Animal的aa对象向下转型成猫对象 13 } 14 } 15 } 16 17 class Animal{ 18 private String name; 19 public Animal(String name){ 20 this.name=name; 21 }//构造方法 22 public void eat(){ 23 24 } 25 public void sleep(){ 26 System.out.println("睡觉 "); 27 } 28 29 } 30 31 class Dog extends Animal{ 32 public Dog(String name){ 33 super(name); 34 } 35 public void eat(){ 36 System.out.println("啃骨头"); 37 } 38 public void sleep(){ 39 System.out.println("睡觉"); 40 } 41 } 42 43 44 class Cat extends Animal{ 45 public Cat(String name){ 46 super(name); 47 } 48 public void eat(){ 49 System.out.println("吃鱼"); 50 } 51 52 public void sleep(){ 53 System.out.println("睡觉"); 54 } 55 56 }
记住 :父类的引用变量变量只能调用父类中有的方法或子类重写父类的方法
向下转型是不安全的
静态绑定在编译期进行 动态绑定实在运行时进行
java中static final private 构造方法都不能被改写
多态性是指同一操作(某一方法)作用于某一类对象(动物),可以有不同的结解释(重写),产生不同的执行结果。例如不同平台下按F1时有不同的解释
多态存在的三个必要条件
1 需要存在继承和实现的关系
2 同样的方法调用而执行不同操作,运行不同的代码(重写操作)
3 在运行时父类或者接口的引用变量必须引用其子类的对象
多态的作用
1多态通过分离做什么和怎么做,重另一个角度将接口和实现进行分离
2多态消除了类型之间的耦合关系
3多态的存在提高了程序的可扩展性和后期的可维护性
接口
1接口(interface)是抽象方法和常量值的定义的集合
2从本质上来讲,接口是一类特殊的抽象类,这种抽象类中只包含常量和方法的定义,而没有变量和方法的实现
3接口中申明的属性默认为public static final 也只能是public static final的
4接口中只能定义抽象方法 而且这些方法默认为public的 也只能是public的、
5接口可以继承其他接口 并添加新的属性和抽象方法
6多个无关类可以实现同一个接口 一个类可以实现多个无关接口 接口与接口之间可以相互继承
1 interface Singer { 2 public void sing(); 3 public void sleep(); 4 } 5 interface Painter { 6 public void paint(); 7 public void eat(); 8 } 9 class student implements Singer { 10 private String name; 11 public student (String name) { 12 this.name = name; 13 } 14 public void study() { 15 System.out.println("Studying"); 16 17 } 18 public void sing() { 19 System.out.println("student is a singer"); 20 } 21 public void sleep() { 22 System.out.println("student can sleep"); 23 24 } 25 26 } 27 class Teacher implements Singer , Painter { 28 private String name; 29 Public Teacher(String name) { 30 this.name = name; 31 } 32 33 public void sing() { 34 System.out.println("teacher is a singer"); 35 } 36 public void sleep() { 37 System.out.println("teacher can sleep"); 38 } 39 public void paint() { 40 System.out.println("teacher is a painter"); 41 } 42 43 public void eat() { 44 System.out.println("teacher can eating"); 45 } 46 47 } 48 49 public class Test { 50 51 public static void main(String []args){ 52 Singer s1 = new student("lili"); 53 s1.sing(); 54 s1.sleep(); 55 Singer s2 = new teacher("steven"); 56 s2.sing(); 57 s2.sleep(); 58 painter p1 = (Painter)s2;//从不同角度去看同一对象 59 p1.paint(); 60 p1.eat(); 61 } 62 63 } 64
2017-07-04 21:08:24