java学习之匿名内部类与包装类
匿名内部类:
所谓匿名内部类,顾名思义指的就是定义在类内部的匿名类,现有的spring框架开发以及java图形界面都经常用到匿名内部类。
下面来看一个代码:
interface A{ public void fun() ; } class B implements A{ public void fun(){ System.out.println("Hello World!!!") ; } }; class X{ public void fun1(A a){ a.fun() ; } public void fun2(){ this.fun1(new B()) ; } }; public class NonameDemo01{ public static void main(String args[]){ new X().fun2() ; } };如果这是实际开发,那么上面的代码存在什么问题?
在了解匿名类之前我们可能只能这样写来实现所需功能,但java语法允许通过设置匿名内部类来去除B类定义(因为B类只会使用一次,单独定义较为浪费)。
interface A{ public void fun() ; } class X{ public void fun1(A a){ a.fun() ; } public void fun2(){ this.fun1(new A(){ public void fun(){ System.out.println("Hello World!!!") ; } }) ; } }; public class NonameDemo02{ public static void main(String args[]){ new X().fun2() ; } };
包装类:
java遵从一切皆对象的原则,那么基本数据类型也应该可转为对象进行操作,这就是类的包装。
在jdk1.5之前,类的包装需要手工转换,
public class IntegerDemo01{ public static void main(String args[]){ int i = 10 ; Integer i2 = new Integer(i) ; // 装箱操作 int j = i2.intValue() ; // 拆箱操作 System.out.println(j * j) ; } };
jdk1.5之后,可自动执行包装与拆装
public class IntegerDemo01{ public static void main(String args[]){ int i = 10 ; Integer i2 = i ; // 装箱操作 int j = i2 ; // 拆箱操作 System.out.println(j * j) ; } };
三个常用Interger方法
public class IntegerSize { public static void main(String[] args) { System.out.println(Integer.MAX_VALUE);//值为 2<sup>31</sup>-1 的常量 System.out.println(Integer.MIN_VALUE);//值为 -2<sup>31</sup> 的常量 System.out.println(Integer.SIZE);//数据类型位数 } }将字符串转换成int/float/double类型,借助parse(Int/Float/Double)
public class Integerint { public static void main(String[] args) { String s="123"; int i = Integer.parseInt(s); System.out.println(++i); } }
转载请注明原文链接!