java 协变性和兼容性

来源:互联网 发布:湖南卫视直播软件 编辑:程序博客网 时间:2024/05/19 05:33

数组的协变性(covariant)是指:

如果类Base是类Sub的基类,那么Base[]就是Sub[]的基类。

 

/*
 * 数组类型的兼容性
 */
public class Test {
 public static void main(String args[]){
  Person per[]=new Employee[5];
  per[0]=new Student();
  ((Student) per[0]).print();
 }
}

class Person{
 
}


class Employee extends Person{
 public void printt(){
  System.out.println("i am employee");
 }
}

 

运行结果:Exception in thread "main" java.lang.ArrayStoreException: Student
 at Test.main(Test.java:7)

 

#####################################

数组和集合都有协变形,但是反省没有

示例:

import java.util.ArrayList;
import java.util.List;

/*
 * java中集合是否有协变形测试
 *
 */

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

  
  /*
   * 泛型,集合泛型都不具有协变形的
   */
  TotalArea ta=new TotalArea();
  List<Circle> u=new ArrayList<Circle>();
  u.add(new Circle(3));
  Shap[] x=new Shap[1];
  x[1]=new Circle(3);

//集合有协变形
  System.out.println(ta.getTotal(x));

//泛型没有,这儿会提示报错。
  System.out.println(ta.getTotalArea(u));
 }
}

class TotalArea{
 public float getTotalArea(List<Shap> u){
  float t=0;
  for(Shap e: u)
   t=((Shap) e).getArea()+t;
  return t;
 }
 
 public float getTotal(Shap[] x){
  float t=0;
  for(Shap e: x)
   t=((Shap) e).getArea()+t;
  return t;
 }
}

class Shap{
 
 public float getArea(){
  return 1;
 }
 
}

class Circle extends Shap{
 private int r;
 Circle(int r){
  this.r=r;
 }
 
 public float getArea(){
  return (float) (3.14*r*r);
 }
 
}

class SanJiao extends Shap{
 private int l;
 private int h;
 SanJiao(int l,int h){
  this.l=l;
  this.h=h;
 }
 
 public float getArea(){
  return (float) (h*l/2);
 }
 
}

 

 

0 0
原创粉丝点击