2019-10-09:1_4

/**

* 使用Object表示泛型

*

* java 的基本思想就是可以通过使用像Object这样适当的超类来实现泛型类

*/

public class p1_4_1

{

public static void main(String[] args)

{

MemoryCell m=new MemoryCell();

m.write("37");

String val= (String) m.read();

System.out.println("contents are:"+val);

}

}


/**

* 基本类型包装

*

* 我们已有一种类型对象,可是语言语法需要一种不同类型对象.

* 典型用法就是存储一个基本类型,并添加一些这种基本类型不支持或不能正确支持的操作.

*/

public class p1_4_2

{

public static void main(String[] args)

{

MemoryCell m=new MemoryCell();

m.write(new Integer(37));

Integer wrapperVal= (Integer) m.read();

int val =wrapperVal.intValue();

System.out.println("contents are:"+val);

}


/**

* 使用接口类型表示泛型

*

* 只有在使用object类中已有的那些方法能够表示所执行的操作的时候,才能使用object作为泛型类型来工作.

*/

public class p1_4_3

{

public static Comparable findMax(Comparable[] arr)

{

int maxIndex=0;

for(int i=1;i

{

if(arr[i].compareTo(arr[maxIndex])>0)

{

maxIndex=i;

}

}

return arr[maxIndex];

}

/**

*  test findMax on shape and string objects.

*/

    public static void main(String[] args)

{

Shape[] shapes={new Circle(2),new Square(3),new Rectangle(4)};

String[] strings={"joe","bob","bill","zeke"};

System.out.println(findMax(shapes));

System.out.println(findMax(strings));

}

}


/**

* 语言数组类型的兼容性

*

* 语言设计中的困难之一是如何处理集合类型的继承问题.

* 设Rectangle IS-A Shape,那么是不是意味Rectangle[] IS-A Shape[]?

*/

public class p1_4_4

{

public static void main(String[] args)

{

/**

        * 两句都编译,而shapes[0]实际上引用了一个Circle,可是Rectangle IS-N-A Circle.

        * 这样就产生了类型混乱,运行时系统(runtime system)不能抛出ClassCastException,因为不存在类型转换.

        * 避免这种问题的最容易的方法是指定这些数组不是类型兼容的,但是在Java中数组却是类型兼容的.

        * 这叫做 '协变数组类型(covariant array type)'.

        * 每个数组都确定它所允许存储的对象的类型.如果插入一个不兼容的类型,虚拟机将抛出一个ArrayStoreException异常.

*/

        Shape[] shapes=new Circle[5];//编译: arrays are compatible(兼容的)

        shapes[0]=new Circle(2);//编译: Circle IS-A Shape

        shapes[1]=new Rectangle(1);//ArrayStoreException

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • DAY 05 1、 public classArrayDemo { public static void mai...
    周书达阅读 728评论 0 0
  • C#(C-Sharp)是Microsoft的新编程语言,被誉为“C/C++家族中第一种面向组件的语言”。然而,不管...
    浮生岁月阅读 3,768评论 0 7
  • 2014年的苹果全球开发者大会(WWDC),当Craig Federighi向全世界宣布“We have new ...
    yeshenlong520阅读 2,309评论 0 9
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,718评论 0 3
  • 创建一个球员类,并且该类最多只允许创建十一个对象。提示利用 static 和 封装性来完成。 [必做题]类的说明...
    多啦A梦_0213阅读 1,264评论 0 0