201871010116- Qi British Red "object-oriented programming (java)" study concluded Week 11

Bowen beginning of the text format: (2 points)

project

content

"Object-oriented programming (java)"

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

Where this requirement in the job

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

Job learning objectives

  1. Understand the generic concepts;
  2. Master the definition and use of generic classes;
  3. Master the declaration and the use of generic methods;
  4. Grasp the definition and implementation of generic interface;
  5. Learn generic programming, understand their purpose.

Essay Bowen body content include:

Part I: summary of Chapter VIII of the theoretical knowledge generic programming (25 points)

1, generic programming concept

(1) increase in generic types in JDK 5.0, the Java language is an important type of safety improvements.

(2) generic: also called a parameterized type (parameterized type), that is, the definition of classes, interfaces and methods, indicating the type of object to be processed by the type parameter. (E.g. ArrayList class) 

(3) generic programming (Generic programming): write code may be reused by many different types of objects.

2, and examples of generic class declaration of method

(1) a generic class (generic class) is having one or more types of the class variables, i.e., the type used as a parameter class created.

(2) As a generic class defined in the following format: class Generics <K, V> where K and V are variable parameter class type.

(3) Pair class introduces a variable of type T, (<>) enclosed in angle brackets, and follows the class name.

(4) generic class can have a plurality of types of variables. For example: public class Pair <T, U> {...}

(5) type variable in the class definition specifies the return type and field, local variable type.

(6) the constraints and limitations of generic classes:

a) can not be used to instantiate the basic type parameter type

b) run-time type query applies only to the original type

c) not throw generic class instance can not be captured

d) parameterized type of array is not legitimate

e) type variable can not instantiate

f) a generic class type variable static context is invalid

g) post-conflict erased attention

Definition 3, the generic method

(1) a generic method: in addition to the generic class, one can define only a single generic method as a method, a method for specifying a generic type parameter or a return value, the method determines that the call left.

(2) may be declared in the generic method generic class can be declared in the general category.

{class ArrayTool public 
     public static <E> void INSERT (E [] E, I int) 
     { 
          // add the code yourself, please 
    } 
 public static <E> E valueAt (E [] E, I int) 
     { 
          // add your own Code 
      } 
}

4, the definition of generic interface

 public interface IPool <T> 
 {
      T get();
      int add(T t); 
 }  

Define (1) the type variable

Upper bound a) defining generic variables

public class NumberGeneric< T extends Number>

b) the lower bound of the defined type variable

List<? superCashCard> cards = new ArrayList<T>();

5, generic type of inheritance rules

(1) Java array is the covariant (covariant), but this principle does not apply to a generic type

(2) Java generic class of non-covariance.

(3) can be extended generic class or implement other generic class.

6, the type and method of use wildcards

(1) "?" Symbol indicates the type of parameter can be of any type, meaning it and T argument is different. T represents an unknown type, and "?" Represents any type. This wildcard generally have the following three uses:

a) alone? , Used to mean any type of

b)? extends type, expressed with the upper bound. 

c)? super type, expressed with a lower bound.

(2) the type defined wildcards 

a)Pair<? extends Employee>

b)  Pair<? super Manager>

c) indefinite wildcard: Pair <?>. <?> Pair Pair that with different: You can call the original method setObject Pair class with any Object object.

Part II: Experimental part

Experiment 1 :  introducing Chapter 8 sample programs, test procedures and code comments.

Test Procedure 1:

Editing, debugging, running textbook 311,312 page code, combined result of the program understand the program;

Add comments to the generic class definitions and use code at;

Grasp the definition and use of generic classes.

Code is as follows:

PairTets1:

pair1 Package; 

/ ** 
 * @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); 
      System.out.println ( "min =" + mm.getFirst ()); 
      System.out.println ( "max =" + mm.getSecond ()); 
   } 
} 

class ArrayAlg 
{ 
	/ ** 
	     * Get string array minimum and maximum values. . 
	     * @Param Array of strings AN A 
	     * @return having a minimum and maximum of, if the null A null or empty, for the  
     * /
   public static Pair < 
   { 
      IF (A == null || a.length == 0) return null; 
      String min = A [0]; 
      String A = max [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 new Pair <> (min, max); 
   } 
}

Pair:

pair1 Package; 

/ ** 
 * @version 1.00 2004-05-10 
 * @author Cay Horstmann 
 * / 
public class Pair <T> // defines a generic class that introduces a variable of type T 
{ 
   Private First T; 
   SECOND T Private; 
 // use the variable type, the return type of the method of the type specified variable 
   public Pair () {First = null; SECOND = null;} 
   public Pair (T First, SECOND T) = {First this.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;} 
}

  Program results are as follows:

Pair class introduces a variable of type T, (<>) enclosed in angle brackets, and follows the class name. Generic class can have a plurality of types of variables. For example, the class may be defined Pair, wherein the first domain and a second domain use different types:

public class Pair<T,U> {......} 

Return type and the type field and local variables in the class definition of the methods specified variable type. For example: private T first; // uses the type variable

A particular type of alternative types of variables can be instantiated generic type, for example: Pair <String> 

Test Procedure 2:

Editing, debugging and running textbooks 315 PairTest2, combined result of the program understand the program;

In generic programming code at add relevant comments;

Learn generic method and generic definition of variables defined purposes.

Code is as follows:

PairTest2:

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), // K. Zuse
         };
      Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);  //实例化对象mm
      System.out.println("min = " + mm.getFirst());
      System.out.println ( "max =" + mm.getSecond ()); 
   }
}

ArrayAlg class 
{ 
	 / ** 
	                       get the minimum and maximum values of type T array objects. 
	       @param T type object array 
	       @return having a minimum and maximum, if A is null or empty, for the null 
    * / 
   public static <T the extends the 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 new Pair <> (min , max); 
   } 
} 

Pair:

pair2 Package; 

/ ** 
 * @version 1.00 2004-05-10 
 * @author Cay Horstmann 
 * / 
public class Pair <T> // defines a generic class that introduces a variable of type T 
{ 
   Private First T; 
   SECOND T Private; 
 // use the variable type, the return type of the method of the type specified variable 
   public Pair () {First = null; SECOND = null;} 
   public Pair (T First, SECOND T) = {First this.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;} 
}  

Program results are as follows:

 

Generic methods can be defined in the general category, can also be defined in generic classes, when calling a generic method, into a specific type of angle brackets in front of the method name:. String middle = ArrayAlg <String> getMiddle ( "John", "Q.", "Public")

; In this case, method call may be omitted <String> type parameter.

Generic generic class definition, valid in the whole class. If the method is used, then the generic class of specific types of objects to be operated clear of all types to be operated has been fixed.

In order to allow different ways to operate different types, and the type is uncertain. Generics can then be defined on the method.

* extends E: E may receive E type or sub-type of the upper limit.
* super E: parent type E or type E may receive a lower limit.

Test Procedure 3:

With commissioning textbooks 335 PairTest3, combined result of the program understand the program;

Understanding Wildcard type definition and uses.

 Code is as follows:

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);
      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 Result <Super Manager?>) 
   { 
      minmaxBonus (A, Result); 
      PairAlg.swapHelper (Result); // SavaHelp captures wildcard type 
   } 
// Can not write public static <T super manager> ... 
} 

class PairAlg 
{ 
   public static boolean hasNulls (Pair <?> the p-) 
   { 
      return p.getFirst () == null || the p-. getSecond () == null; 
   } 

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

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

Pair:

pair3 Package; 

/ ** 
 * @version 1.00 2004-05-10 
 * @author Cay Horstmann 
 * / 
public class Pair <T> // defines a generic class that introduces a variable of type T 
{ 
   Private First T; 
   SECOND T Private; 
 // use the variable type, the return type of the method of the type specified variable 
   public Pair () {First = null; SECOND = null;} 
   public Pair (T First, SECOND T) = {First this.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;} 
}

Employee:

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;
   }
}

Manager:

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;
   }
}

  Program results are as follows:

When you want to use a generic class, generic class that should pass a type argument, if there is no actual parameter passed in time, the compiler will propose a generic warning.

On the use of wildcards:

Use wildcards in the API relatively tricky, but wildcards can make many flexible API code.

If you write a library widely used, it must be appropriate to use wildcards. Wildcard there is a principle, namely:. Producer-extends, consumer-super (PECS) is a typical producer, consumer model problem.

 To represent the various generic List parent class, the type of wildcards can be used, question mark as a set of arguments passed to type List, writing (?): List (meaning List element type is unknown), the elements of this question mark "?" type can match any type.

Experimental Summary: (15 points)

By learning this week, I learned about generic programming, generic class and generic methods along with reuse, type safety and efficiency, generic class will not be forced to carry on boxing and unboxing value types, or reference types are cast down, so to improve programming performance. I think the advantages of generic programming is to write code that can be many different reused types of objects. Reducing the amount of code, and increased readability. In learning theory class, listening to the teacher generic class is not particularly difficult, but when you run the program on the experimental course, not too understanding of the program, in their own programming, there are still a big problem. After the study, I will practice more programs to understand this knowledge.

Guess you like

Origin www.cnblogs.com/qyhq/p/11818609.html