201871010126 왕 Yatao "객체 지향 프로그래밍 (자바)"연구는 11 주 결론

계획

함유량

이 작품은 과정 속

https://www.cnblogs.com/nwnu-daizh/

어디에서 작업이 요구 사항

https://www.cnblogs.com/nwnu-daizh/p/11815810.html

작업 학습 목표

학습 목표

1. 매스터 자바 예외 처리 기술;

사용의 주장을 이해합니다;

로그의 목적을 이해합니다;

4. 마스터 프로그램 기본 디버깅 기술.

제 VIII 제네릭 프로그래밍

8.1 왜 제네릭 프로그래밍을 사용하여

8.1.1 제네릭 클래스 정의

일반 클래스 (일반 클래스) 클래스 변수 중 하나 개 이상의 타입을 갖는된다, 즉 타입은 매개 변수로 클래스를 생성하는데 사용. 다음 형식으로 정의 된 일반적인 클래스로
      클래스 제네릭 <K, V>
 파라미터 K 및 V 클래스이고 가변형.

1) .Pair 클래스 형식의 변수 T (<>)로 묶 소개하고, 클래스 이름 각괄호 따른다.

2). 일반 클래스는 변수 복수 종류를 가질 수있다. 예를 들면 : 

공용 클래스 쌍 <T의 U-> {...} 

3) 클래스 타입 변수 방법 및 필드 타입, 리턴 지정

로컬 변수의 종류.

8.1.2 일반적인 방법 문

1). 일반적인 클래스 이외에, 한 방법으로는 단지 하나의 일반적인 방법을 정의 할 수 있으며, 일반 타입 인자 또는 리턴 값을 지정하기위한 방법은 호출이 남아 있는지를 판정한다.

 2). 일반 방법은 일반 클래스에서 선언 할 수는 일반 카테고리에서 선언 할 수있다.

 

 

 8.1.3 일반적인 인터페이스 정의

1) 정의

 

 

 2) 상한 유형의 변수를 정의

공용 클래스 NumberGeneric <T는 번호를 확장>

. 소정 NumberGeneric 일반 클래스 변수 유형 위의 문 상속 관계 및 처리 될 수있다;


어퍼 클래스가 모두 될 수 있습니다 선언 키워드 b.extends을 결합, 그것은 또한 인터페이스가 될 수 있습니다.

3).는 입력 변수 정의의 하한

가 하부 유형 설명 변수의 하한

–通过使用super关键字可以固定泛型参数的类型为
 
1)、某种类型的超类;
 
2)、当希望为一个方法的参数限定类型时,通常可以使用下限通配符;
 
8.1.4  通配符
 “?”符号表明参数的类型可以是任何一种类型,它和参数T的含义是有区别的。T表示一种未知类型,而“?”表示任何一种类型。这种通配符一般有以下三种用法:

(1)单独的?,用于表示任何类型。

(2)? extends type,表示带有上界。

(3) ? super type,表示带有下界。
 
8.1.5无限定的通配符
 
例如,Pair<?>。Pair<?>与Pair的不同在于:可以用任意Object对象调用原始的Pair类的setObject方法.

1、实验目的与要求

(1) 理解泛型概念;

(2) 掌握泛型类的定义与使用;

(3) 了解泛型方法的声明与使用;

(4) 掌握泛型接口的定义与实现;

(5) 理解泛型程序设计,理解其用途。

2、实验内容和步骤

实验1 导入第8章示例程序,测试程序并进行代码注释。

测试程序1:

编辑、调试、运行教材311312页代码,结合程序运行结果理解程序;

在泛型类定义及使用代码处添加注释;

掌握泛型类的定义及使用。

实验代码如下:

package pair1;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class Pair<T> //pair类引入了一个类型变量T
{
   private T first;
   private T second;

   public Pair() { first = null; second = null; }//无参构造器
   public Pair(T first, T second) { this.first = first;  this.second = second; }

   public T getFirst() { return first; }
   public T getSecond() { return second; }

   public void setFirst(T newValue) { first = newValue; }
   public void setSecond(T newValue) { second = newValue; }
}
package pair1;

/**
 * @version 1.01 2012-01-26
 * @author Cay Horstmann
 */
public class PairTest1
{
   public static void main(String[] args)
   {
      String[] words = { "Mary", "had", "a", "little", "lamb" };
      Pair<String> mm = ArrayAlg.minmax(words);//类名调用,minmax是static静态方法
      System.out.println("min = " + mm.getFirst());
      System.out.println("max = " + mm.getSecond());
   }
}

class ArrayAlg
{
   /**
    * Gets the minimum and maximum of an array of strings.//获得数组的最大值与最小值
    * @param a an array of strings
    * @return a pair with the min and max values, or null if a is null or empty
    */
   public static Pair<String> minmax(String[] a)
   {
      if (a == null || a.length == 0) return null;//空引用和空数组
      String min = a[0];
      String max = a[0];
      for (int i = 1; i < a.length; i++)
      {
         if (min.compareTo(a[i]) > 0) min = a[i];
         if (max.compareTo(a[i]) < 0) max = a[i];
      }
      return new Pair<>(min, max);//返回新队
   }
}

实验截图如下:

 

 泛型类的定义与使用:

泛型类:public class Demo<T> {} ,T表示未知类型。
泛型接口:public interface ImplDemo<T,V>{} ,和定义类一样(接口就是一个特殊类)。
泛型方法:public <T>  void demo1(T name){System.out.println(name);} , public <T> T demo2(T t){ return t;}

测试程序2:

编辑、调试运行教材315 PairTest2,结合程序运行结果理解程序;

在泛型程序设计代码处添加相关注释;

了解泛型方法、泛型变量限定的定义及用途。

程序代码如下:

package pair2;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class Pair<T> //pair类引入了一个类型变量T
{
   private T first;
   private T second;

   public Pair() { first = null; second = null; }
   public Pair(T first, T second) { this.first = first;  this.second = second; }

   public T getFirst() { return first; }
   public T getSecond() { return second; }

   public void setFirst(T newValue) { first = newValue; }
   public void setSecond(T newValue) { second = newValue; }
}

 

package pair2;

import java.time.*;

/**
 * @version 1.02 2015-06-21
 * @author Cay Horstmann
 */
public class PairTest2
{
   public static void main(String[] args)
   {
      LocalDate[] birthdays = 
         { 
            LocalDate.of(1906, 12, 9), // G. Hopper
            LocalDate.of(1815, 12, 10), // A. Lovelace
            LocalDate.of(1903, 12, 3), // J. von Neumann
            LocalDate.of(1910, 6, 22),
            };//初始化一个localDate对象,名为birthdays
      Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);//静态方法可以通过类名调用
      System.out.println("min = " + mm.getFirst());
      System.out.println("max = " + mm.getSecond());
   }
}

class ArrayAlg
{
   /**
      Gets the minimum and maximum of an array of objects of type T.//获取T类型对象数组的最小值和最大值
      @param a an array of objects of type T
      @return a pair with the min and max values, or null if a is null or empty
   */
   public static <T extends Comparable> Pair<T> minmax(T[] a) 
   {
      if (a == null || a.length == 0) return null;
      T min = a[0];
      T max = a[0];
      for (int i = 1; i < a.length; i++)
      {
         if (min.compareTo(a[i]) > 0) min = a[i];
         if (max.compareTo(a[i]) < 0) max = a[i];
      }
      return new Pair<>(min, max);
   }
}

运行截图如下:

 

 总结:

1、泛型类定义的泛型,在整个类中有效。如果被方法使用,那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。
2、为了让不同方法可以操作不同类型,而且类型还不确定。那么可以将泛型定义在方法上。

3、特殊之处:

静态方法不可以访问类上定义的泛型。

如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。

测试程序3:

用调试运行教材335 PairTest3,结合程序运行结果理解程序;

了解通配符类型的定义及用途。

实验代码如下:

package pair3;

/**
 * @version 1.01 2012-01-26
 * @author Cay Horstmann
 */
public class PairTest3
{
   public static void main(String[] args)
   {
      var ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);//创建了一个Manager类对象
      var cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
      var buddies = new Pair<Manager>(ceo, cfo);      
      printBuddies(buddies);

      ceo.setBonus(1000000);
      cfo.setBonus(500000);
      Manager[] managers = { ceo, cfo };

      var result = new Pair<Employee>();
      minmaxBonus(managers, result);
      System.out.println("first: " + result.getFirst().getName() 
         + ", second: " + result.getSecond().getName());
      maxminBonus(managers, result);
      System.out.println("first: " + result.getFirst().getName() 
         + ", second: " + result.getSecond().getName());
   }

   public static void printBuddies(Pair<? extends Employee> p)
   {
      Employee first = p.getFirst();
      Employee second = p.getSecond();
      System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
   }

   public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
   {
      if (a.length == 0) return;
      Manager min = a[0];
      Manager max = a[0];
      for (int i = 1; i < a.length; i++)
      {
         if (min.getBonus() > a[i].getBonus()) min = a[i];
         if (max.getBonus() < a[i].getBonus()) max = a[i];
      }
      result.setFirst(min);
      result.setSecond(max);
   }

   public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
   {
      minmaxBonus(a, result);
      PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type//swapHelper捕获通配符类型
   }
   // can't write public static <T super manager> . . .// 不能写公共静态 <T super manager> ...
}

class PairAlg
{
   public static boolean hasNulls(Pair<?> p)//?表示:类型变量通配符
   {
      return p.getFirst() == null || p.getSecond() == null;
   }

   public static void swap(Pair<?> p) { swapHelper(p); }

   public static <T> void swapHelper(Pair<T> p)
   {
      T t = p.getFirst();
      p.setFirst(p.getSecond());
      p.setSecond(t);
   }
}
package pair3;

public class Manager extends Employee
{  
   private double bonus;

   /**
      @param name the employee's name
      @param salary the salary
      @param year the hire year
      @param month the hire month
      @param day the hire day
   */
   public Manager(String name, double salary, int year, int month, int day)
   {  
      super(name, salary, year, month, day);//调用父类的姓名。工资。年。月。日
      bonus = 0;
   }

   public double getSalary()
   { 
      double baseSalary = super.getSalary();
      return baseSalary + bonus;
   }

   public void setBonus(double b)
   {  
      bonus = b;
   }

   public double getBonus()
   {  
      return bonus;
   }
}
package pair3;

import java.time.*;

public class Employee
{  
   private String name;
   private double salary;
   private LocalDate hireDay;

   public Employee(String name, double salary, int year, int month, int day)
   {
      this.name = name;
      this.salary = salary;
      hireDay = LocalDate.of(year, month, day);
   }

   public String getName()
   {
      return name;
   }

   public double getSalary()
   {  
      return salary;
   }

   public LocalDate getHireDay()
   {  
      return hireDay;
   }

   public void raiseSalary(double byPercent)
   {  
      double raise = salary * byPercent / 100;
      salary += raise;
   }
}
package pair1;

/**
 * @version 1.00 2004-05-10
 * @author Cay Horstmann
 */
public class Pair<T> //pair类引入了一个类型变量T
{
   private T first;
   private T second;

   public Pair() { first = null; second = null; }//无参构造器
   public Pair(T first, T second) { this.first = first;  this.second = second; }

   public T getFirst() { return first; }
   public T getSecond() { return second; }

   public void setFirst(T newValue) { first = newValue; }
   public void setSecond(T newValue) { second = newValue; }
}

运行截图如下:

 

 总结:

实验2结对编程练习,将程序提交到PTA2019面向对象程序设计基础知识测试题(2

1 编写一个泛型接口GeneralStack要求类方法对任何引用类型数据都适用。GeneralStack接口中方法如下:

push(item);            //itemnull,则不入栈直接返回null

pop();                 //出栈,如为栈为空,则返回null

peek();                //获得栈顶元素,如为空,则返回null.

public boolean empty();//如为空返回true

public int size();     //返回栈中元素数量

 

2定义GeneralStackArrayListGeneralStack要求:

 

ü 类内使用ArrayList对象存储堆栈数据,名为list

 

ü 方法: public String toString()//代码为return list.toString();

 

ü 代码中不要出现类型不安全的强制转换。

 

3定义Car类,类的属性

 

private int id;

 

private String name;

 

方法:Eclipse自动生成setter/getter,toString方法。

 

4main方法要求

 

ü 输入选项,有quit, Integer, Double, Car 4个选项。如果输入quit程序直接退出。否则,输入整数mnm代表入栈个数,n代表出栈个数。然后声明栈变量stack

 

ü 输入Integer,打印Integer Test。建立可以存放Integer类型的ArrayListGeneralStack。入栈m次,出栈n次。打印栈的toString方法。最后将栈中剩余元素出栈并累加输出。

 

ü 输入Double ,打印Double Test。剩下的与输入Integer一样。

 

ü 输入Car,打印Car Test。其他操作与IntegerDouble基本一样。只不过最后将栈中元素出栈,并将其name依次输出。

 

特别注意:如果栈为空,继续出栈,返回null

输入样例

Integer
5
2
1 2 3 4 5
Double
5
3
1.1 2.0 4.9 5.7 7.2
Car
3
2
1 Ford
2 Cherry
3 BYD
quit

输出样

Integer Test
push:1
push:2
push:3
push:4
push:5
pop:5
pop:4
[1, 2, 3]
sum=6
interface GeneralStack
Double Test
push:1.1
push:2.0
push:4.9
push:5.7
push:7.2
pop:7.2
pop:5.7
pop:4.9
[1.1, 2.0]
sum=3.1
interface GeneralStack
Car Test
push:Car [id=1, name=Ford]
push:Car [id=2, name=Cherry]
push:Car [id=3, name=BYD]
pop:Car [id=3, name=BYD]
pop:Car [id=2, name=Cherry]
[Car [id=1, name=Ford]]
Ford
interface GeneralStack

 

结对编程代码如下:

import java.util.ArrayList;
import java.util.Scanner;
 
interface GeneralStack<T>{
    public T push(T item);            //如item为null,则不入栈直接返回null。
    public T pop();                 //出栈,如为栈为空,则返回null。
    public T peek();                //获得栈顶元素,如为空,则返回null.
    public boolean empty();//如为空返回true
    public int size();     //返回栈中元素数量
}
class ArrayListGeneralStack implements GeneralStack{
    ArrayList list=new ArrayList();
    @Override
    public String toString() {
        return  list.toString();
    }
 
    @Override
    public Object push(Object item) {
        if (list.add(item)){
            return item;
        }else {
            return false;
        }
    }
 
    @Override
    public Object pop() {
        if (list.size()==0){
            return null;
        }
        return list.remove(list.size()-1);
    }
 
    @Override
    public Object peek() {
        return list.get(list.size()-1);
    }
 
    @Override
    public boolean empty() {
        if (list.size()==0){
            return true;
        }else {
            return false;
        }
    }
 
    @Override
    public int size() {
        return list.size();
    }
}
class Car{
    private int id;
    private String name;
 
    @Override
    public String toString() {
        return "Car [" +
                "id=" + id +
                ", name=" + name  +
                ']';
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Car(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
public class Main {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        while (true){
            String s=sc.nextLine();
            if (s.equals("Double")){
                System.out.println("Double Test");
                int count=sc.nextInt();
                int pop_time=sc.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
                for (int i=0;i<count;i++){
                    System.out.println("push:"+arrayListGeneralStack.push(sc.nextDouble()));
                }
                for (int i=0;i<pop_time;i++){
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());
                double sum=0;
                int size=arrayListGeneralStack.size();
                for (int i=0;i<size;i++){
                    sum+=(double)arrayListGeneralStack.pop();
                }
                System.out.println("sum="+sum);
                System.out.println("interface GeneralStack");
            }else if (s.equals("Integer")){
                System.out.println("Integer Test");
                int count=sc.nextInt();
                int pop_time=sc.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
                for (int i=0;i<count;i++){
                    System.out.println("push:"+arrayListGeneralStack.push(sc.nextInt()));
                }
                for (int i=0;i<pop_time;i++){
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());
                int sum=0;
                int size=arrayListGeneralStack.size();
                for (int i=0;i<size;i++){
                    sum+=(int)arrayListGeneralStack.pop();
                }
                System.out.println("sum="+sum);
                System.out.println("interface GeneralStack");
            }else if (s.equals("Car")){
                System.out.println("Car Test");
                int count=sc.nextInt();
                int pop_time=sc.nextInt();
                ArrayListGeneralStack arrayListGeneralStack = new ArrayListGeneralStack();
                for (int i=0;i<count;i++){
                    int id=sc.nextInt();
                    String name=sc.next();
                    Car car = new Car(id,name);
                    System.out.println("push:"+arrayListGeneralStack.push(car));
                }
                for (int i=0;i<pop_time;i++){
                    System.out.println("pop:"+arrayListGeneralStack.pop());
                }
                System.out.println(arrayListGeneralStack.toString());
                if (arrayListGeneralStack.size()>0){
                    int size=arrayListGeneralStack.size();
                    for (int i=0;i<size;i++){
                        Car car=(Car) arrayListGeneralStack.pop();
                        System.out.println(car.getName());
                    }
                }
                System.out.println("interface GeneralStack");
            }else if (s.equals("quit")){
                break;
            }
        }
 
    }
}

 

实验总结:

1):这周我们学习了第八章泛型程序设计中的相关知识点,定义了简单的泛型类,通过上课时老师的讲解和课下学长的讲解,对不会的知识点有了进一步的掌握,对Java这门学科有了更深入的了解。

2):这周的实验有对上周实验的反思,我发现了很多不足。首先接手问题之后的思路不清晰,其次代码编写不够,这周泛型设计的学习,了解到泛型类具备可重用性、类型安全和效率等性质,是程序性能得到提升。课下我还需继续努力。

 

 

추천

출처www.cnblogs.com/wyt0455820/p/11819281.html