201871010114- Li Yansong "object-oriented programming (java)" eighth week learning summary

 

project

content

This work belongs courses

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

Where this requirement in the job

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

Job learning objectives

  1. Master interface defines the method;
  2. Master interface class implementation-defined requirements;
  3. Grasp to achieve the requirements of the interface class;
  4. Callback understand design patterns;
  5. Master Comparator interface usage;
  6. Grasp objects shallow copy and deep copy method;
  7. Master Lambda expression syntax;
  8. Understand the purpose and requirements of internal grammar class.

Part I: The sixth chapter summarizes theoretical knowledge

First, the interface

1.1 interface concept

接口(英文:Interface),在JAVA编程语言中是一个抽象类型,是抽象方法的集合,接口通常以interface来声明。一个类通过继承接口的方式,从而来继承接口的抽象方法。
接口并不是类,编写接口的方式和类很相似,但是它们属于不同的概念。类描述对象的属性和方法。接口则包含类要实现的方法。
除非实现接口的类是抽象类,否则该类要定义接口中的所有方法。
接口无法被实例化,但是可以被实现。一个实现接口的类,必须实现接口内所描述的所有方法,否则就必须声明为抽象类。另外,在 Java 中,接口类型可用来声明一个变量,他们可以成为一个空指针,或是被绑定在一个以此接口实现的对象。

1.2, an interface similar to a class point

一个接口可以有多个方法。
接口文件保存在 .java 结尾的文件中,文件名使用接口名。
接口的字节码文件保存在 .class 结尾的文件中。
接口相应的字节码文件必须在与包名称相匹配的目录结构中。

1.3, the difference between interfaces and classes

接口不能用于实例化对象。
接口没有构造方法。
接口中所有的方法必须是抽象方法。
接口不能包含成员变量,除了 static 和 final 变量。
接口不是被类继承了,而是要被类实现。
接口支持多继承。

1.4 Interface feature

接口中每一个方法也是隐式抽象的,接口中的方法会被隐式的指定为 public abstract(只能是 public abstract,其他修饰符都会报错)。
接口中可以含有常量,但是接口中的变量会被隐式的指定为 public static final 变量(并且只能是 public,用 private 修饰会报编译错误)。 接口中的方法是不能在接口中实现的,只能由实现接口的类来实现接口中的方法。

1.5, the difference between abstract classes and interfaces

抽象类中的方法可以有方法体,就是能实现方法的具体功能,但是接口中的方法不行。
抽象类中的成员变量可以是各种类型的,而接口中的成员变量只能是 public static final 类型的常量。
一个类只能继承一个抽象类,而一个类却可以实现多个接口。

1.6, differences in syntax interfaces and abstract classes:

1)接口不能有构造方法,抽象类可以有。
2)接口不能有方法体,抽象类可以有。
3)接口不能有静态方法,抽象类可以有。
4)在接口中凡是变量必须是public static final,而在抽象类中没有要求。

1.7, static methods and the default method

1、静态方法
在Java SE 8中,允许在接口中增加静态方法。理论上讲 , 没有任何理由认为这是不合法的。只是这有违于将接口作为抽象规范的初衷 。
public interface A { static String aa(){ return "my is A aa"; } } A.aa();//my is A aa
2、默认方法
Java 8 允许给接口添加一个非抽象的方法实现,只需要使用 default 关键字即可,这个特征又叫做扩展方法(也称为默认方法或虚拟扩展方法或防护方法)。在实现该接口时,该默认扩展方法在子类上可以直接使用,它的使用方式类似于抽象类中非抽象成员方法。

默认方法允许我们在接口里添加新的方法,而不会破坏实现这个接口的已有类的兼容性,也就是说不会强迫实现接口的类实现默认方法。

默认方法和抽象方法的区别是抽象方法必须要被实现,默认方法不是。作为替代方式,接口可以提供一个默认的方法实现,所有这个接口的实现类都会通过继承得到这个方法(如果有需要也可以重写这个方法)
public interface A { static String aa(){ return "my is A aa"; } String bb(); default String cc(){ return "my is A cc"; }; default String dd(){ return "my is A dd"; }; } public class B implements A{ @Override public String bb() { return "my is B bb"; } @Override public String cc(){ return "my is B cc"; } }
3、默认方法冲突
如果先在一个接口中将一个方法定义为默认方法,然后又在超类或另一个接口中定义了同样的方法,就会产生一个二义性错误.对于解决这个问题,java提供了相对简单的规则.
1)、超类优先.如果超类提供了一个具体方法,同名并且有相同参数的默认方法会被忽略
2)、接口冲突.如果一个接口提供了一个默认方法,另一个接口提供了一个同名而且参数类型相同的方法,必须覆盖这个方法来解决冲突

Part II: Experimental part

1 , experimental purposes and requirements

(1) Method master interface definition;

(2) master interface class implementation-defined requirements;

(3) master enables the use requirements of the interface class;

(4) callback master design patterns;

(5) master Comparator interface usage;

(6) grasp the object shallow and deep copy copying method;

(7) master Lambda expression syntax;

(8) The use and learn the syntax required within the class.

2 , experimental and step

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

Test Procedure 1:

l editing, compiling, debugging and running Read textbook pages 214-215 page program 6-1, 6-2, to understand the program and analyze the result of the program;

l add a comment new knowledge at the relevant code in the program.

l realize usage control interface;

Package the interfaces; 

Import Classes in java.util *. ; 

/ ** 
 . * This Program The 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) 
   { 
      the Employee [] Staff = new new the Employee [. 3]; // create an array object, the size of the three 

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

      Arrays.sort (Staff); 

      // print all employee object information 
      for (the Employee E: Staff) 
         the System. Out.println ( "name =" e.getName + () + ", the 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;//name访问器
   }

   public double getSalary()
   {
      return salary;   //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);
   }
}

operation result:

 

 Test sample program:

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

operation result: 

 

 

Test Procedure 3:

l commissioning materials 6-3 in elipse IDE 223, the binding result of the program be appreciated program;

l 26 lines, 36 lines refer to 224, relates to materials detailed in Chapter 12.

l add a comment new knowledge at the relevant code in the program.

l master callback programming mode;

package week8;

/**
   @version 1.02 2017-12-14
   @author Cay Horstmann
*/

import java.awt.*;
import java.awt.event.*;
import java.time.*;
import javax.swing.*;

public class TimerTest
{  
   public static void main(String[] args)
   {  
      var listener = new TimePrinter();//定义一个Timeprinter

      // construct a timer that calls the listener
      // once every second
      var timer = new Timer(1000, listener);
      timer.start();

      // keep program running until the user selects "OK"
      JOptionPane.showMessageDialog(null, "Quit program?");
      System.exit(0);
   }
}

class TimePrinter implements ActionListener //ActionListener是TimePrinter的接口
{  
   public void actionPerformed(ActionEvent event)
   {  
      System.out.println("At the tone, the time is " 
         + Instant.ofEpochMilli(event.getWhen()));
      Toolkit.getDefaultToolkit().beep();
   }
}

6-3

 

 

Test Procedure 4:

l commissioning program materials 229 -231 pages 6-4 and 6-5, the program runs in conjunction with the results of the program to understand;

l add a comment new knowledge at the relevant code in the program.

l grasp objects cloning techniques to achieve;

l grasp the deep and shallow copy copy difference.

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);
         //Employee是一个自定义类
         original.setHireDay(2000, 1, 1);
         Employee copy = original.clone();
         copy.raiseSalary(10); // change the original object does not occur 
         copy.setHireDay (2002, 12 is, 31 is); // changer 
         System.out.println ( "Original =" Original +); // string concatenation 
         System.out. the println ( "Copy =" + Copy); 
      } 
      the 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
   {
      // 调用object.clone()
      Employee cloned = (Employee) super.clone();

      // 克隆可变的字段
      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();
      
      // 实力字段突变的例子
      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 + "]";
   }

operation result:

 

 

Experiment 2:  Import Chapter 6 6-6 sample program, learning Lambda expressions usage.

l commissioning textbook pages 233-234 pages 6-6 program, run in conjunction with the results of the program to understand the program;

l add a comment new knowledge at the relevant code in the program.

The lines l and Comparative materials 27-29 223 program, the 27-29 line with this procedure contrast, appreciate the advantages of Lambda expression.

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();   
         
      // 持续运行程序直到按下ok键
      JOptionPane.showMessageDialog(null, "Quit program?");
      System.exit(0);         
   }
}

operation result:

 

 

Note: The following experiment after-school completion

Experiment 3: Programming Exercises

l preparation of a program, the information read in the ID number .txt into memory;

l lexicographically by name information outputting the art;

l query maximum age of personnel information;

l inquiry youngest personnel information;

 

package week8;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

public class Main{
    private static ArrayList<Person> Personlist;
    public static void main(String[] args) {
         Personlist = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("D:\\java\\身份证号.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(fis));
            String temp = null;
            while ((temp = in.readLine()) != null) {
                
                Scanner linescanner = new Scanner(temp);
                
                linescanner.useDelimiter(" ");    
                String name = linescanner.next();
                String ID = linescanner.next();
                String sex = linescanner.next();
                String age = linescanner.next();
                String place =linescanner.nextLine();
                Person  people = new Person();
                people.setname(name);
                people.setID(ID);
                people.setsex(sex);
                int a = Integer.parseInt(age);
                people.setage(a);
                people.setbirthplace(place);
                Personlist.add(people);

            }
        } catch (FileNotFoundException e) {
            System.out.println("查找不到信息");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("信息读取有误");
            e.printStackTrace();
        }
        boolean isTrue = true;
        while (isTrue) {
            System.out.println("----------------------------------------" ); 
            System.out.println ( "1: output staff by name lexicographical information" ); 
            System.out.println ( "2: query the maximum age of the youngest personnel information and personnel information" ); 
            System.out.println ( "3: are there people in your query fellow " ); 
            System.out.println ( " 4: enter your age, the age of the query with all the information you recently people " ); 
            System.out.println ( " 5: exit program " ); 
            
            int nextInt = Scanner. the nextInt ();
             Switch (the nextInt) {
             Case . 1 : 
                the Collections.sort (personList); 
                System.out.println (personList.toString());
                break;
            case 2:
                
                int max=0,min=100;int j,k1 = 0,k2=0;
                for(int i=1;i< Personlist.size();i++)
                {
                    j= Personlist.get(i).getage();
                   if(j>max)
                   {
                       max=j; 
                       k1=i;
                   }
                   if(j<min)
                   {
                       min=j; 
                       k2=i;
                   }

                }  
                System.out.println("年龄最大:"+ Personlist.get(k1));
                System.out.println("年龄最小:"+ Personlist.get(k2));
                break;
            case 3:
                System.out.println("place?");
                String find = scanner.next();        
                String place=find.substring(0,3);
                String place2=find.substring(0,3);
                for (int i = 0; i < Personlist.size(); i++) 
                {
                    if( Personlist.get(i).getbirthplace().substring(1,4).equals(place)) 
                        System.out.println(Personlist.get(i));

                } 

                break;
            case 4:
                System.out.println("年龄:");
                int yourage = scanner.nextInt();
                int near=agenear(yourage);
                int d_value=yourage-Personlist.get(near).getage();
                System.out.println(""+Personlist.get(near));
           /*     for (int i = 0; i < Peoplelist.size(); i++)
                {
                    int p=Personlist.get(i).getage()-yourage;
                    if(p<0) p=-p;
                    if(p==d_value) System.out.println(Peoplelist.get(i));
                }   */
                break;
            case 5:
           isTrue = false;
           System.out.println("退出程序!");
                break;
            default:
                System.out.println("输入有误");
            }
        }
    }
    public static int agenear(int age) {
     
       int min=25,d_value=0,k=0;
        for (int i = 0; i <  Personlist.size(); i++)
        {
            d_value= Personlist.get(i).getage()-age;
            if(d_value<0) d_value=-d_value; 
            if (d_value<min) 
            {
               min=d_value;
               k=i;
            }

         }    return k;
        
     }

 
}
package week8;

public  class  Person implements Comparable<Person > {
private String name;
private String ID;
private int age;
private String sex;
private String birthplace;

public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID= ID;
}
public int getage() {

return age;
}
public void setage(int age) {
    // int a = Integer.parseInt(age);
this.age= age;
}
public String getsex() {
return sex;
}
public void setsex(String sex) {
this.sex= sex;
}
public String getbirthplace() {
return birthplace;
}
public void setbirthplace(String birthplace) {
this.birthplace= birthplace;
}

public int compareTo(Person  o) {
   return this.name.compareTo(o.getname());

}

public String toString() {
    return  name+"\t"+sex+"\t"+age+"\t"+ID+"\t"+birthplace+"\n";
    }

operation result:

 

 

Experiment 4: inner class syntax validation experiments

Experimental Procedure 1:

l editing, debugging and running programs teaching 246 -247 pages 6-7, combined result of the program understand the program;

l understand the basic usage within the class.

 

 

 

Experimental Procedure 2:

l editing, debugging and running programs teaching 254 6-8 combined result of the program understand the program;

l master the use of anonymous inner classes.

 

 

Experimental Procedure 3:

l commissioning textbook pages 257 -258 program elipse IDE 6-9, in conjunction with the results of running the program understanding;

l understand the usage of static inner classes.

Experimental summary

This chapter learned to master the interface definition method; implement the requirements defined interface class; implements the interface requirements of the class; callback design patterns; Comparator Interface usage; shallow copy and deep copy the object method; Lambda expression syntax; inner class The use and syntax. Through code annotation of new knowledge, to understand more clearly. But I feel the programming mode callback I can not fully understand, I will be back access to information, conduct further study.

 

Guess you like

Origin www.cnblogs.com/liyansong0198/p/11715987.html