面向对象(匿名对象的概述与应用)

什么是匿名对象?

  • 没有名字的对象

匿名对象应用场景

  • 调用方法,仅仅只调用一次的时候

  节省代码

  注意:调用多次的时候,不适合。匿名对象调用完毕就是垃圾。可以被垃圾回收器回收

  • 匿名对象可作为实际参数传递

匿名对象只适合对方法的一次调用,因为调用多次就会产生多个对象,不如用有名字的对象

匿名对象是否可以调用属性并赋值?有什么意义?

匿名对象可以调用属性,但是没有意义,因为调用后就变成垃圾

如果需要赋值还是用有名字对象

public class Test05 {
    public static void main(String[] args) {
//        Car c1 = new Car();//创建有名字的对象
//        c1.run();
//        c1.run();
//        
//        new Car().run(); //匿名对象调用方法
        
        new Car().color = "red";
        new Car().num = 8;
        new Car().run();
        
    }

}

class Car{
    String color;
    int num;
    
    public void run() {
        System.out.println(color + "车运行" + num);
    }
}

运行结果:null车运行0

匿名对象作为实际参数传递实例:

public class Test06 {
    public static void main(String[] args) {
        method(new Car());//匿名对象可以当作参数传递
    }
    //抽取方法提高代码的复用性
    public static void method(Car cc) {
        cc.color = "red";
        cc.num = 8;
        cc.run();
    }

}

class Car{
    String color;
    int num;
    
    public void run() {
        System.out.println(color + "车运行" + num);
    }
}

运行结果:red车运行8

补充实例:匿名内部类

public class Test11 {
    public static void main(String[] args) {
        int[] arr = {8,9,3,6,33,88,10};
//        class SubCmp extends comparator{
//            public int compare(int x1, int x2) {
//                return x1 - x2;
//            }
//        }
//        comparator cmp = new SubCmp();
//        bubbleSort2(arr,cmp);
     //等同一其他语言中的回调函数callback
//定义comparator的匿名子类,同时用new 创建对象, new后面的是父类名 bubbleSort2(arr, new comparator(){ public int compare(int x1, int x2) { //奇偶数的判断步骤 if(x1 % 2 == 0) { return 1; } return -1; } }); System.out.println(Arrays.toString(arr)); } public static int[] bubbleSort2(int[] array, comparator cmp) { for (int i = 0; i < array.length - 1; i++) { for (int j = 0; j < array.length - 1 - i; j++) { if(cmp.compare(array[j], array[j + 1]) > 0) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } // if(array[j] > array[j + 1]) { // int temp = array[j]; // array[j] = array[j + 1]; // array[j + 1] = temp; // } } } return array; } static class comparator{ public int compare(int x1, int x2) { return x2 - x1; } } //冒泡排序 public static int[] bubbleSort(int[] array, boolean orderType) { for (int i = 0; i < array.length - 1; i++) { for (int j = 0; j < array.length - 1 - i; j++) { if(orderType) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } }else { if (array[j] < array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } return array; } }
原文地址:https://www.cnblogs.com/happystudyhuan/p/10702014.html