1. 程式人生 > >201771010101 白瑪次仁 《2018面向物件程式設計(Java)》第八週

201771010101 白瑪次仁 《2018面向物件程式設計(Java)》第八週

實驗六 介面的定義與使用

實驗時間 2018-10-18

1、實驗目的與要求

(1) 掌握介面定義方法

(2) 掌握實現介面類的定義要求;

(3) 掌握實現了介面類的使用要求;

(4) 掌握程式回撥設計模式;

(5) 掌握Comparator介面用法;

(6) 掌握物件淺層拷貝與深層拷貝方法;

(7) 掌握Lambda表示式語法;

(8) 瞭解內部類的用途及語法要求。

學習總結:

1. 介面:用interface宣告,是抽象方法和常量值定義的集 合。從本質上講,介面是一種特殊的抽象類。

(1)在Java程式設計語言中,介面不是類,而是對類 的一組需求描述,由常量和一組抽象方法組成。 l 介面中不包括變數和有具體實現的方法。

(2)介面體中包含常量定義和方法定義,介面中只進 行方法的宣告,不提供方法的實現。

(3)通常介面的名字以able或ible結尾;

(4)介面中的所有常量必須是public static final,方法必須是public abstract,這是 系統預設的,不管你在定義介面時,寫不寫 修飾符都是一樣的.

(5)介面的實現:一個類使用了某個介面,那麼這個類必須實現該 介面的所有方法,即為這些方法提供方法體。一個類可以實現多個介面,介面間應該用逗號分 隔開。

(6)介面的使用:介面不能構造介面物件,但可以宣告介面變數以指向一個實現了該介面的類物件。

(7)可以用instanceof檢查物件是否實現了某個介面。

(8)抽象類:用abstract來宣告,沒有具體例項物件的類,不 能用new來建立物件。

2. 介面示例

(1)回撥(callback):一種程式設計模式,在這種模 式中,可指出某個特定事件發生時程式應該採取 的動作。

(2)Comparator介面所在包: java.util.*

(3)Object類的Clone方法:當拷貝一個物件變數時,原始變數與拷貝變數 引用同一個物件。這樣,改變一個變數所引用 的物件會對另一個變數產生影響。

(4)如果要建立一個物件新的copy,它的最初狀態與 original一樣,但以後可以各自改變狀態,就需 要使用Object類的clone方法。

(5)Object.clone()方法返回一個Object物件。必須進行強 制型別轉換才能得到需要的型別。

(6)淺層拷貝與深層拷貝

(7)Java中物件克隆的實現:在子類中實現Cloneable介面。

(8)在子類的clone方法中,呼叫super.clone()。

3. lambda表示式

(1)Java Lambda 表示式是 Java 8 引入的一個新的功能,主 要用途是提供一個函式化的語法來簡化編碼。

(2)Lambda 表示式的語法基本結構 (arguments) -> body

(3)有如下幾種情況: 1、引數型別可推導時,不需要指定型別,如 (a) -> System.out.println(a)  

2、 只有一個引數且型別可推導時,不強制寫 (), 如 a -> System.out.println(a)    

3、 引數指定型別時,必須有括號,如 (int a) -> System.out.println(a)    

4、引數可以為空,如 () -> System.out.println(“hello”)    

5、 body 需要用 {} 包含語句,當只有一條語句時 {} 可省略

4.內部類:是定義在一個類內部的類。

2、實驗內容和步驟

實驗1 匯入第6章示例程式,測試程式並進行程式碼註釋。

測試程式1:

編輯、編譯、除錯執行閱讀教材214-215頁程式6-16-2,理解程式並分析程式執行結果;

在程式中相關程式碼處新增新知識的註釋。

掌握介面的實現用法;

掌握內建介面Compareable的用法。

package interfaces;

import java.util.*;

/**
 * This program demonstrates the use of the Comparable interface.
 * @version 1.30 2004-02-27
 * @author Cay Horstmann
 */
public class EmployeeSortTest
{
   public static void main(String[] args)
   {
      Employee[] staff = new Employee[3];//普通陣列

      staff[0] = new Employee("Harry Hacker", 35000);
      staff[1] = new Employee("Carl Cracker", 75000);
      staff[2] = new Employee("Tony Tester", 38000);

      Arrays.sort(staff);//靜態方法sort

      // print out information about all Employee objects
      for (Employee e : staff)
         System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
   }
}

 

package interfaces;

 

public class Employee implements Comparable<Employee>

{

   private String name;

   private double salary;

 

   public Employee(String name, double salary)

   {

      this.name = name;

      this.salary = salary;

   }

 

   public String getName()

   {

      return name;

   }

 

   public double getSalary()

   {

      return salary;

   }

 

   public void raiseSalary(double byPercent)

   {

      double raise = salary * byPercent / 100;

      salary += raise;

   }

 

   /**

    * Compares employees by salary

    * @param other another Employee object

    * @return a negative value if this employee has a lower salary than

    * otherObject, 0 if the salaries are the same, a positive value otherwise

    */

   public int compareTo(Employee other)

   {

      return Double.compare(salary, other.salary);

   }

}

 

 

 

測試程式2

編輯、編譯、除錯以下程式,結合程式執行結果理解程式;

interface  A

{

  double g=9.8;

  void show( );

}

class C implements A

{

  public void show( )

  {System.out.println("g="+g);}

}

 

class InterfaceTest

{

  public static void main(String[ ] args)

  {

       A a=new C( );

       a.show( );

       System.out.println("g="+C.g);

  }

}

public interface  A
    {
      double g=9.8;
      void show( );
    }
 
class C implements A
{
  public void show( )
  {System.out.println("g="+g);}
 
}
 
package InterfaceTest;
public class InterfaceTest {
     public static void main(String[ ] args)
      {
           A a=new C( );
           a.show( );
           System.out.println("g="+C.g);
      }
    }
 

 

 

 

 

 

測試程式3

elipse IDE中除錯執行教材2236-3,結合程式執行結果理解程式;

l 26行、36行程式碼參閱224頁,詳細內容涉及教材12章。

在程式中相關程式碼處新增新知識的註釋。

掌握回撥程式設計模式;

package timer;

 

/**

   @version 1.01 2015-05-12

   @author Cay Horstmann

*/

 

import java.awt.*;

import java.awt.event.*;

import java.util.*;

import javax.swing.*;

import javax.swing.Timer;

// to resolve conflict with java.util.Timer

 

public class TimerTest

{  

   public static void main(String[] args)

   {  

      ActionListener listener = new TimePrinter();

 

      // construct a timer that calls the listener

      // once every 10 seconds

      Timer t = new Timer(10000, listener);

      t.start();

 

      JOptionPane.showMessageDialog(null, "Quit program?");

      System.exit(0);

   }

}

 

class TimePrinter implements ActionListener

{  

   public void actionPerformed(ActionEvent event)

   {  

      System.out.println("At the tone, the time is " + new Date());

      Toolkit.getDefaultToolkit().beep();

   }

}

 

 

測試程式4

除錯執行教材229-231頁程式6-46-5,結合程式執行結果理解程式;

在程式中相關程式碼處新增新知識的註釋。

掌握物件克隆實現技術;

掌握淺拷貝和深拷貝的差別。

package clone;

 

/**

 * This program demonstrates cloning.

 * @version 1.10 2002-07-01

 * @author Cay Horstmann

 */

public class CloneTest

{

   public static void main(String[] args)

   {

      try

      {

         Employee original = new Employee("John Q. Public", 50000);

         original.setHireDay(2000, 1, 1);

         Employee copy = original.clone();

         copy.raiseSalary(10);

         copy.setHireDay(2002, 12, 31);

         System.out.println("original=" + original);

         System.out.println("copy=" + copy);

      }

      catch (CloneNotSupportedException e)

      {

         e.printStackTrace();

      }

   }

}

package clone;

 

import java.util.Date;

import java.util.GregorianCalendar;

 

public class Employee implements Cloneable

{

   private String name;

   private double salary;

   private Date hireDay;

 

   public Employee(String name, double salary)

   {

      this.name = name;

      this.salary = salary;

      hireDay = new Date();

   }

 

   public Employee clone() throws CloneNotSupportedException

   {

      // call Object.clone()

      Employee cloned = (Employee) super.clone();

 

      // clone mutable fields

      cloned.hireDay = (Date) hireDay.clone();

 

      return cloned;

   }

 

   /**

    * Set the hire day to a given date.

    * @param year the year of the hire day

    * @param month the month of the hire day

    * @param day the day of the hire day

    */

   public void setHireDay(int year, int month, int day)

   {

      Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime();

      

      // Example of instance field mutation

      hireDay.setTime(newHireDay.getTime());

   }

 

   public void raiseSalary(double byPercent)

   {

      double raise = salary * byPercent / 100;

      salary += raise;

   }

 

   public String toString()

   {

      return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";

   }

}

 

實驗2 匯入第6章示例程式6-6,學Lambda表示式用法。

除錯執行教材233-234頁程式6-6,結合程式執行結果理解程式;

在程式中相關程式碼處新增新知識的註釋。

27-29行程式碼與教材223頁程式對比,將27-29行程式碼與此程式對比,體會Lambda表示式的優點。

package lambda;

 

import java.util.*;

 

import javax.swing.*;

import javax.swing.Timer;

 

/**

 * This program demonstrates the use of lambda expressions.

 * @version 1.0 2015-05-12

 * @author Cay Horstmann

 */

public class LambdaTest

{

   public static void main(String[] args)

   {

      String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",

            "Jupiter", "Saturn", "Uranus", "Neptune" };

      System.out.println(Arrays.toString(planets));

      System.out.println("Sorted in dictionary order:");

      Arrays.sort(planets);

      System.out.println(Arrays.toString(planets));

      System.out.println("Sorted by length:");

      Arrays.sort(planets, (first, second) -> first.length() - second.length());

      System.out.println(Arrays.toString(planets));

            

      Timer t = new Timer(1000, event ->

         System.out.println("The time is " + new Date()));

      t.start();   

         

      // keep program running until user selects "Ok"

      JOptionPane.showMessageDialog(null, "Quit program?");

      System.exit(0);         

   }

}

 

實驗總結:通過這次是實驗更好地瞭解介面。