匿名对象 前几天课上的

来源:互联网 发布:皖西学院网络课程 编辑:程序博客网 时间:2024/06/01 22:57
/*匿名对象:1.当对对象方法仅进行一次调用的时2.匿名对象可以作为实际参数进行传递*/class MyMath{double getPI(){return 3.1415;}}class Tools{void printPI(MyMath m){System.out.println(m.getPI());}}class NiMingDemo {public static void main(String[] args) {//1.当对对象方法仅进行一次调用的时// MyMath math = new MyMath();double pi = new MyMath().getPI();//匿名对象,new之后直接访问成员属性或成员方法;System.out.println(pi);System.out.println(pi);System.out.println("--------------------------");//2.2.匿名对象可以作为实际参数进行传递Tools tools = new Tools();// MyMath math = new MyMath();tools.printPI(new MyMath());//将匿名对象传递到方法;因为我们的程序内不需要MyMath的引用;//将上述两种方式集成new tools().printPI(new MyMath());}}
0 0
原创粉丝点击