面向對象-------------匿名對象(六)

1.什麼是匿名對象
    * 沒有名字的對象
2.匿名對象應用場景
    * a:調用方法,僅僅只調用一次的時候。
        * 那麼,這種匿名調用有什麼好處嗎?
            * 節省代碼
        * 注意:調用多次的時候,不適合。匿名對象調用完畢就是垃圾。可以被垃圾回收器回收。
    * b:匿名對象可以作爲實際參數傳遞

匿名對象與有名字的對象的區別:

匿名對象只適合對方法的一次調用,因爲調用多次就會產生多個對象,不如用有名字的對象   


class Demo2_Car {
	public static void main(String[] args) {
		/*Car c1 = new Car();			//創建有名字的對象
		c1.run();
		c1.run();

		new Car().run();			//匿名對象調用方法
		new Car().run();	*/		//匿名對象只適合對方法的一次調用,因爲調用多次就會產生多個對象,不如用有名字的對象	
	
	}
}

class Car {
	String color;			//顏色
	int num;				//輪胎數

	public void run() {
		System.out.println(color + "..." + num);
	}
}

匿名對象是否可以調用屬性並賦值?有什麼意義?

匿名對象可以調用屬性,但是沒有意義,因爲調用後就變成垃圾.如果需要賦值還是用有名字對象


class Demo2_Car {
	public static void main(String[] args) {
		/*Car c1 = new Car();			//創建有名字的對象
		c1.run();
		c1.run();

		new Car().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);
	}
}

匿名對象當做參數

class Demo3_Car {
	public static void main(String[] args) {
		//Car c1 = new Car();//地址值
		/*c1.color = "red";
		c1.num = 8;
		c1.run();*/
		//method(c1);

		method(c1);

		//Car c2 = new Car();
		//method(c2);
		method(new Car());		//匿名對象可以當作參數傳遞
	}

	//抽取方法提高代碼的複用性
	public static void method(Car cc) {	//Car cc = new Car();  我這個方法 聲明的是 我要的是Car對象
		cc.color = "red";
		cc.num = 8;
		cc.run();
	}
}

class Car {
	String color;			//顏色
	int num;			//輪胎數

	public void run() {
		System.out.println(color + "..." + num);
	}
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章