JavaExam

Contents.png

Java基本编译操作

$ javac HelloWorld.java
$ java HelloWorld

类,对象

  • What is a Java class?
    ➢ A template for a new data type (一种数据类型,即对象类型)
      – If you write a class, objects of that class’s type can be constructed and used.
    ➢ A code module(模块)
        - Class是面相对象程序设计中 最基本的程序单元。
      – A module is a unit of program code.
      – Putting code in separate classes separates your program’s functionality.
    ➢ Arrays in Java
      – Not pointers, like C, but first-class objects 
        – Checked at run-time for safety
      – Covered later
    
  • Object

    Everything is an Object.
    
  • Literals

    - Boolean Literals
    ➢ There are only two: true 、 false
    
    - Underscores (_) in Numeric Literals
    ➢ any number of underscore characters (_) can appear anywhere between digits in a numerical literal
      – cannotplaceunderscoresinthefollowingplaces:
      ➢ At the beginning or end of a number
      ➢ Adjacent to a decimal point in a floating point literal ➢ Prior to an F or L suffix
      ➢ In positions where a string of digits is expected
      
    - Binary Literals
    ➢ the integral types (byte, short, int, and long) can also be expressed using the binary number system.   – Java SE 7
    ➢ add the prefix 0b or 0B to the number
    
  • static Method

    ➢ What if you want a method that can be called for the class, without an object? (“class method”)
        
        class StaticFun {
           static void incr() {       WithStaticData.x++;     }   // 不可被重写,不能是抽象方法
         }
         StaticFun.incr();
    
  • Annotations

    ➢ @Override:限定重写父类
    ➢ @Deprecated:标记已过时
    ➢ @SuppressWarning:抑制编译器警告 
    ➢......
    
  • Overloading 重载

    - Unique combinations of argument types distinguish overloaded methods
    ➢ One word, many meanings: overloaded
    
    - Overloading with primitives
    ➢ if you have a data type that is smaller than the argument in the method, that data type is promoted 
    ➢ if your argument is bigger than the argument expected by the overloaded method, you must cast to the necessary type by placing the type name inside parentheses.
      – If you don’t do this, the compiler will issue an error message
      – narrowing conversion
    
    - no Overloading on return values
    
    - Default constructors: Takes no Arguments
    ➢ Compiler automatically creates one for you if you write no constructors
    if you define any constructors (with or without arguments), the compiler will not synthesize(合成) one for you
    
  • The meaning of static

    ➢ there is no this for that particular method // 不支持this
    ➢ cannot call non-static methods from inside static methods   // psvm
    ➢ you can call a static method for the class itself, without any object 类名调用static方法
    
    if you find yourself using a lot of static methods, you should probably rethink your strategy // 尽可能少地使用static方法
    
  • finalize()

    ➢ Using finalize() to detect an object that hasn't been properly cleaned up.
    ➢ finalize() is only useful for obscure memory cleanup that most programmers will never use. // 善后
    

包 Package

➢ A package is a collection of functionally related 'classes' and 'interfaces' providing access protection and namespace management.    (定义)

➢ Managing “name spaces”
– Class members are already hidden inside class
– Class names could clash(类名冲突)
– Need completely unique name even over the Internet(名称唯一)

➢ Creating unique package names (独一无二的包名)
– Location on disk encoded into package name
– bruceeckel.com (Note change to lowercase 'com') 
    package com.bruceeckel.util;
    
➢ Legalizing Package Names  ('域名'与'包名'完全逆序)
    Domain Name → Package Name Prefix
    hyphenated-name.example.org → org.example.hyphenated_name
    example.int → int_.example

➢ 'import' the constants and static methods
    – do not need to prefix the name of their class (无需重写包名as前缀)

➢ “Friendly”  (同一个包内,任意调用类方法或类成员)
    - Default access, has no keyword (Also referred to as "package access")
    - public to other members of the same package, private to anyone outside the package
 ➢ AccessControl
 public: Interface Access
 private: Can’t Touch That!
 protected: deals with inheritance
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N

继承 inheritance

继承是子类利用父类中定义的方法和变量就像它们属于子类本身一样。
方法的覆盖:在子类中重新定义父类中已有的方法。

通过在类的声明中加入extends子句来创建一个类的子类. 
如果缺省extends子句,则该类为java.lang.Object的子类。

子类可以继承父类中访问权限设定为public、 protected、 default的成员变量和方法。
但是不能继承访问权限为private的成员变量和方法。

方法覆盖(overriding)指子类对 父类的方法进行改写
子类覆盖的方法同父类的方法要保持名称、返回值类型、 参数列表的统一。
• 改写后的方法不能比被覆盖的方法 有更严格的访问权限
• 改写后的方法不能比被覆盖的方法 产生更多的异常
  • Upcasting ("向上"类型转换)

  • The final Keyword

    ➢ "This cannot be changed"
        
    ➢ A bit confusing: two reasons for using it 
      – Design
      – Efficiency
    
    ➢ final data ➢ 修饰变量,变量就变成了常量;
    ➢ final methods ➢ 修饰方法,方法就'不'能再'覆盖'; 
    ➢ final class ➢ 修饰类,类就'不'能再'继承'.
    
    ➢ final arguments
      void f(final int i) { // ...
        - Primitives can’t be changed inside method
              void g(final Bob b) {
                    b = new Bob(); (错 × ) // 不可更改
                }
        - References can’t be rebound inside method
        - Generally, neither one is used
    
  • Pure Inheritance vs. Extension

    -  Pure Inheritance  “Is a” 
      •Cannot extend the interface (不扩展)
           
    - Extension
      • Extending the interface (扩展,加入新方法)
    

多态 polymorphism

➢ Dynamic Binding in Java
binding occurs at run time, based on the type of object. Late binding is also called dynamic binding or run-time binding.
    
    
 * 隐式调用 super() 时,radius为0  (父类调用重写方法,子类成员变量还未初始化)
 * 子类重写后,new子类对象--调用子类重写后的方法
 
     
➢ 执行顺序
1. 主函数所在类中的static字段\代码块(而非static 方法),若该类为子类,则先执行父类中的static字段,再执行该类的static字段
2. main()主函数
3. new Cat()  
     3.1> 隐含调用 Animal() 父类构造方法 (先加载父类成员\代码块(先static后non-static);后加载构造函数)
     3.2> 加载 Cat类的成员变量、代码块 (先static后non-static)
     3.3> 顺序执行 Cat() 的构造方法  // 构造函数总是类的最后被调用,类中的方法不加载

抽象类 abstract class

 definition: Java classes that cannot be instantiated! 
  //抽象类不能被实例化,如果被实例化,就会报错,编译无法通过。只有抽象类的非抽象子类可以创建对象
 conceptually: a hybrid(混合) of a Java class and interface  

* 一个类只能继承一个抽象类,而一个类却可以实现多个接口
  • 抽象方法
- bstract关键字同样可以用来声明抽象方法,抽象方法只包含一个方法名,而没有方法体。
- 抽象方法没有定义,方法名后面直接跟一个分号,而不是花括号

声明抽象方法会造成以下两个结果:
- 如果一个类包含抽象方法,那么该类'必须是抽象类'
- 任何子类必须重写父类的抽象方法,或者声明自身为抽象类

- 抽象类的非抽象子类必须实现抽象类中的抽象方法
  • Summary
1. 抽象类不能被实例化,如果被实例化,就会报错,编译无法通过。只有抽象类的非抽象子类可以创建对象。
2. 抽象类中不一定包含抽象方法,但是有抽象方法的类必定是抽象类。
3. 抽象类中的抽象方法只是声明,不包含方法体,就是不给出方法的具体实现也就是方法的具体功能。
4. 构造方法,类方法(用static修饰的方法)不能声明为抽象方法。 // important
5. 抽象类的子类必须给出抽象类中的抽象方法的具体实现,除非该子类也是抽象类。

接口 Interface

- 接口(英文:Interface),在JAVA编程语言中是一个抽象类型,是'抽象方法'的集合,接口通常以interface来声明。一个类通过实现接口的方式,从而来继承接口的抽象方法 
    
- 一个实现接口的类,必须实现接口内所描述的'所有方法',否则就必须声明为'抽象类'.

- 接口特性
    - 接口'无法实例化对象'.
    - 接口'没有构造方法'.
    - 接口中所有的方法必须是'抽象方法'.(方法'隐式抽象'为 public abstract,不能在接口中实现)
        and default and static methods (需实现)
    - 接口'不能包含成员变量',除了 static 和 final 变量.(隐式指定为 public static final members)
    - 接口不是被类继承了,而是要被类'实现'.
    - 接口支持'多“继承”'(via 'implements'关键字). (补充:一个接口能继承另一个接口(使用'extends'关键字))
   
- Using an Interface as a Type
    public static void t(CanFight x) { x.fight(); }     // CanFight is interface

- 接口可以嵌套在类中,也可以嵌套在其他接口中
  • Default Methods (可以被重写)

  • Static Methods (不可被继承)

Generic

class NewPair<S, T> {   // Notice!(class)
        private S first;
        private T second;

        public NewPair(S a, T b) {
            first = a;
            second = b;
        }

        public S getFirst() {
            return first;
        }

        public T getSecond() {
            return second;
        }
    }

------------------------------------------------------------
    public static <T extends Comparable<T>>   
        int countGreaterThan(T[] anArray, T elem) {    //  <T extends Comparable<T>> (method)
        int count = 0;
        for (T e : anArray)
            if (e.compareTo(elem) > 0)      // e.compareTo(elem)
                ++count;
        return count;
    }
------------------------------------------------------------
-  <T extends Comparable<? super T>>

Inner Classes

/** 内部类其实严重破坏了良好的代码结构,但为什么还要使用内部类呢?
因为内部类可以随意使用外部类的成员变量(包括私有)而不用生成外部类的对象,这也是内部类的唯一优点。
如同心脏可以直接访问身体的血液,而不是通过医生来抽血。**/

Out.In in = new Out().new In(); //class Out{ class In{ } }  // 内部类的基本结构
Out.In in = new Out.In();   //class Out{ static class In{ } }   // 静态内部类
Out out = new Out(); out.outPrint();    // 私有内部类
/*class Out{ 
    private class In{ 
        public void print() {
            System.out.println(age);
        } 
    }  
    public void outPrint() {
        new In().print();
    }
}*/
Out out = new Out();  out.Print(3);     // 方法内部类
//class Out{ public void Print(final int x) { class In{ } } }

Exception机制

  • Exception 类是 Throwable 类的子类。除了Exception类外,Throwable还有一个子类Error

    异常类有两个主要的子类:IOException 类和 RuntimeException 类.

img
  • finally关键字

    无论是否发生异常,finally 代码块中的代码总会被执行。
    
    - 在 try/catch 后面添加 finally 块并非强制性要求的。
    - try 代码后不能既没 catch 块也没 finally 块
    
  • try-with-resources

    try-with-resources语句是一个声明了1到多个资源的try语句。资源是指这个try执行完成后必需close掉的对象,比如connection, resultset等。
    
    try-with-resources 语句会确保在try语句结束时关闭所有资源。实现了java.lang.AutoCloseable或java.io.Closeable的对象都可以做为资源。
    

Java数据结构

Arrays

// 声明数组  - Null reference
double[] myList;         // 首选的方法 
或
double myList[];         //  效果相同,但不是首选方法

// 创建数组
dataType[] arrayRefVar = new dataType[arraySize];
或
dataType[] arrayRefVar = {value0, value1, ..., valuek};

//Variable Size Array:
     int x[][] = new int[3][];
     x[0] = new int[2];
     x[1] = new int[4];
     x[2] = new int[3];

// wrong example
int table[][]={0,0,0,1,1,1};    (×)
int table[2][3]={0,0,0,1,1,1};  (×)
// Right example
int table[ ][ ]={{0,0,0},{1,1,1}}; (√)

//- Once initialized, the array size is fixed
- Arrays.equals(int[] a, int[] a2): compare two arrays for equality  "比较值相等"
– Arrays.copyOf(int[] original, int newLength): copy specified array
- Arrays.asList((T... a): takes any array and turns it into a List container
- Arrays.fill(int[] a, int val) 
- Arrays.sort(int[] a)
- Arrays.binarySearch(int[] a, int key)     // array must be sorted ; return the index of key

String

- Strings → Numbers
    float a = (Float.valueOf("1")).floatValue();
    float b = Float.parseFloat("1");    // a == b (1.0)
- Numbers → Strings
    String s1 = "" + i;
    String s2 = String.valueOf(i);
    String s3 = Integer.toString(i);
String.equal.png

Collection

img
- Java集合框架为程序员提供了预先包装的数据结构和算法来操纵他们。
- 集合是一个对象,可容纳其他对象的引用。集合接口声明对每一种类型的集合可以执行的操作。
- 集合框架的类和接口均在java.util包中。
- 任何对象加入集合类后,自动转变为Object类型,所以在取出的时候,需要进行强制类型转换。
Container taxonomy - simplified.png
Implementation-style.png
  • 遍历 ArrayList

    public class Test{
     public static void main(String[] args) {
         List<String> list=new ArrayList<String>();
         list.add("Hello");
         list.add("World");
         list.add("HAHAHAHA");
         //第一种遍历方法使用foreach遍历List
         for (String str : list) {  //或 for(inti=0;i<list.size();i++)
            System.out.println(str);
         }
     
         //第二种遍历,把链表 → 数组相关的内容进行遍历
         String[] strArray=new String[list.size()];
         list.toArray(strArray);
         for(int i=0;i<strArray.length;i++) //或for(String str:strArray)
         {
            System.out.println(strArray[i]);
         }
         
        //第三种遍历 使用迭代器iterator进行相关遍历
         Iterator<String> ite = list.iterator();
         while(ite.hasNext())//判断下一个元素之后有值
         {
             System.out.println(ite.next());
         }
     }
    }
    
  • 遍历 Map

    public class Test{
         public static void main(String[] args) {
          Map<String, String> map = new HashMap<String, String>();
          map.put("1", "value1");
          map.put("2", "value2");
          map.put("3", "value3");
          
          //第一种:普遍使用,二次取值
          System.out.println("通过Map.keySet遍历key和value:");
          for (String key : map.keySet()) {
           System.out.println("key= "+ key + " and value= " + map.get(key));
          }
          
          //第二种
          System.out.println("通过Map.entrySet使用iterator遍历key和value:");
          Iterator<Map.Entry<String, String>> it= map.entrySet().iterator();
          while (it.hasNext()) {
           Map.Entry<String, String> entry = it.next();
           System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
          }
          
          //第三种:推荐,尤其是容量大时
          System.out.println("通过Map.entrySet遍历key和value");
          for (Map.Entry<String, String> entry : map.entrySet()) {
           System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
          }
        
          //第四种
          System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
          for (String v : map.values()) {
           System.out.println("value= " + v);
          }
         }
    }
    

Java IO系统

// InputStreamReader
public static void main(String[] args) {
InputStreamReader isr = new InputStreamReader(System.in); 
    int c;
        try {
            while ((c = isr.read()) != -1)
                System.out.println((char) c);
        } catch(IOException e) {
            //... 
        }
}

// BufferedReader
public static void main(String[] args) { 
    BufferedReader br =
new BufferedReader(new InputStreamReader(System.in)); 
    String s;
    try {
        while ((s = br.readLine()).length() != 0) 
        System.out.println(s);
         } catch(IOException e) {
               //...
        }
}

对象序列化

// Serialization Example - Reading
try {
    InputStream is = new FileInputStream(“file.txt”);
    ObjectInputStream ois = new ObjectInputStream(is);
    ArrayList someList = (ArrayList)ois.readObject();
    is.close();
  } catch (Exception e) { ... }


// Serialization Example - Writing
try {
    OutputStream os = new FileOutputStream(“file.txt”);
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(someList); 
    oos.flush();
    os.close();
  } catch (IOException ioe) { ... }

NIO

AWT, Swing

public class FrameTester {      //  JFrame Example
            public static void main(String args[]) {
                JFrame f = new JFrame("JFrame Example");
                Container c = f.getContentPane();   
                c.setLayout(new FlowLayout());  // default BorderLayout
                for (int i = 0; i < 5; i++) {
                    c.add(new JButton("No"));
                    c.add(new Button("Batter"));
                }
                c.add(new JLabel("Swing"));
                f.setSize(300, 200);
                f.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        }
//JOptionPane
class Addition {

    public static void main(String args[]) {

// obtain user input from JOptionPane input dialogs

        String firstNumber =
                JOptionPane.showInputDialog("Enter first integer");

        String secondNumber =
                JOptionPane.showInputDialog("Enter second integer");

        // convert String inputs to int values for use in a calculation
        int number1 = Integer.parseInt(firstNumber);
        int number2 = Integer.parseInt(secondNumber);

        int sum = number1 + number2; // add numbers


        // display result in a JOptionPane message dialog
        JOptionPane.showMessageDialog(null, "The sum is " + sum,
                "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE);
    } // end method main

}

JDBC

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbUtil {   // conn.createStatement()

    public static final String URL = "jdbc:mysql://localhost:3306/imooc";
    public static final String USER = "liulx";
    public static final String PASSWORD = "123456";

    public static void main(String[] args) throws Exception {
        //1.加载驱动程序 load database driver class
        Class.forName("com.mysql.jdbc.Driver");
        //2. 获得数据库连接 connect to database
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        //3.Create a SQL statement object)
        Statement stmt = conn.createStatement();
        // 4. Getting data from a table
        ResultSet rs = stmt.executeQuery("SELECT user_name, age FROM imooc_goddess");
        //5. Use methods of ResultSet (如果有数据,rs.next()返回true)
        while(rs.next()){
            System.out.println(rs.getString("user_name")+" 年龄:"+rs.getInt("age"));  // rs.getString("user_name") / rs.getInt("age")
        }
    }
}
-------------------------------------------------
public class TestDB {   // conn.preparedStatement(sql)

    public static final String URL = "jdbc:mysql://localhost:3306/imooc";
    public static final String USER = "liulx";
    public static final String PASSWORD = "123456";
    
    public static void main(String[] args) throws Exception {

        //1.加载驱动程序 load database driver class
        Class.forName("com.mysql.jdbc.Driver");

        //2. 获得数据库连接 connect to database
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);

        //3.Create a SQL statement object)
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT * FROM TODO");

        // 4. Getting data from a table
        ResultSet resultSet = preparedStatement.executeQuery();

        //5. Use methods of ResultSet (如果有数据,rs.next()返回true)
        while (resultSet.next()) {
            System.out.println(resultSet.getInt(1));
            System.out.println(resultSet.getString(2));
        }
    }
}

java多线程

class Thread implements Runnable{}
- 实现 Runnable 接口来创建线程 
new Thread(Runnable threadOb,String threadName).start;
--------------------------------------
Talker talker = new Talker(); 
Thread t = new Thread(talker); 
t.start();
---
     class Talker implements Runnable {
       public void run() {
         while (true) {
           System.out.println(“Talker”);
            } 
       }
}

--------------------------------------------------------
- 继承Thread来创建线程
ThreadDemo T1 = new ThreadDemo( );
T1.setName("Thread-1");
T1.start();

void start()
    – Creates a new thread and makes it runnable (包含于Thread,继承的类亦可重写)
void run()
    – The new thread begins its life inside this method (继承的类必须实现)
- synchronized methods

class Account {
        private int balance;

        public synchronized void deposit(int val) {
            int newBal;
            newBal = balance + val;
            balance = newBal;
        }

        public void withdraw(int val) {
            synchronized(this) {
            int newBal;
            newBal = balance - val;
            balance = newBal;
            }
        }
    }
Deadlock
- Four Conditions of Deadlock
- Avoiding Deadlock
    - The easiest way to prevent deadlock is to break the fourth condition.
- Wait/Notify Sequence  (均在Object中定义)

1. synchronized(lock){
2.      lock.wait();
9.      consumeResource();
10. }

3. produceResource()
4. synchronized(lock){
5.      lock.notify(); 
6.}

7. Reacquire lock // 重新唤醒锁
8. Return from wait()
//  ForkJoin Framework
    ForkJoinPool pool = new ForkJoinPool();

    RecursiveTask<List<String>> recursiveTaskInstance = CountByForkJoin.getInstance(list, 5);   // 实例化

    ForkJoinTask<List<String>> future = pool.submit(recursiveTaskInstance);     // 提交可分解的ForkJoinTask任务

        // do something

    pool.shutdown(); 

java网络编程

TCP Socket

protocol localAddr,localPort remoteAddr, remotePort
conn-oriented server ServerSocket() accept()
conn-oriented client Socket()
connectionless server DatagramSocket() receive()
connectionless client DatagramSocket() send()
conn-oriented server
// 1. Create ServerSocket object
ServerSocket serverSocket = new ServerSocket(port);  

// 2. Server listens for client connection  (多于client的步骤)
Socket server = serverSocket.accept();
System.out.println("远程主机地址:" + server.getRemoteSocketAddress());

// 3. Sending and receiving data    (先read后write)
DataInputStream in = new DataInputStream(server.getInputStream());
DataOutputStream out = new DataOutputStream(server.getOutputStream());

// 4. Server and Client communicate via streams
System.out.println(in.readUTF());   // in.readUTF()
out.writeUTF("谢谢连接我:" + server.getLocalSocketAddress() + "\nGoodbye!");     //out.writeUTF("something")  


// 5. Close streams and connections
server.close();
conn-oriented client
// 1. Create a Socket to connect to server
Socket client = new Socket(serverName, port);   
System.out.println("远程主机地址:" + client.getRemoteSocketAddress());

// 2. Obtain Socket’s InputStream and Outputstream (先write后read)
OutputStream outToServer = client.getOutputStream();
InputStream inFromServer = client.getInputStream();
DataOutputStream out = new DataOutputStream(outToServer);
DataInputStream in = new DataInputStream(inFromServer);

// 3. Process information communicated
out.writeUTF("Hello from " + client.getLocalSocketAddress());   //out.writeUTF("something")
System.out.println("服务器响应: " + in.readUTF()); // in.readUTF()

// 4. Close streams and connection
client.close();

Lambda 表达式

public void printSighting(Sighting record){System.out.println(record.getDetails()); }
等价于                          
(Sighting record) ->
{ System.out.println(record.getDetails()); }      

for(Sighting record : sightings) { printSighting(record);}
等价于
sightings.forEach((Sighting record) ->                               {System.out.println(record.getDetails()); }
 );

➢ infer type (缺省type)
sightings.forEach((record) ->
    {System.out.println(record.getDetails()); }
);
➢ single parameter (缺省参数括号)
sightings.forEach(record ->
    {System.out.println(record.getDetails()); }
);
➢ single statement (缺省body大括号)
sightings.forEach(record -> System.out.println(record.getDetails()));
➢ Aggregate Operations 
roster
    .stream()
    .filter(
        p -> p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25) 
    .map(p -> p.getEmailAddress())
    .forEach(email -> System.out.println(email));

STREAMS

There are three common types of operation:
– Filter: select items from the input stream to pass on to the output stream
– Map: replace items from the input stream with different items in the output stream
– Reduce: collapse the multiple elements of the input stream into a single element
A stream pipeline .png

Summary

  • Summary of Initialization & Cleanup

    ➢ Initialization is critical for objects, thus Java guarantees it with the constructor
    ➢ Knowing when to clean up can be difficult in complex systems
    ➢ Java GC releases memory only: any other cleanup must be done explicitly!
    ➢ Arrays also have Java-style safety
    

  • Summary of Hiding the Implementation

    ➢ Access control tells users what they can & can‟t use (shows the area of interest)
    ➢ Also separates interface & implementation
    ➢ Allows the class creator to change the implementation later without disturbing client code
    ➢ An important design & implementation flexibility
    ➢ Design guideline: always make elements “as private as possible”
    
  • Summary of Reusing Classes

    ➢ Easy to think that OOP is only about inheritance
    ➢ Often easier and more flexible to start with composition. Remember to say “has-a” and “is-a”
    ➢ Use inheritance when it’s clear that a new type is a kind of a base type
    ➢ ... and especially when you discover a need for polymorphism (next chapter)
    
  • Summary: The Key to OOP

OOP_key.png
  • AbstractClass & Interfaces

    ➢ abstract类定义方法,实现公共的方法。
    ➢ 接口(interface)就是'方法声明'和'常量值'的集合。 
    – An interface defines a protocol of communication between two objects.
    – 从本质上讲,接口是一种特殊的抽象类,这种抽象类中只包含常量的定义( public static final members)和方法的声明(public abstract),而没有变量和方法的实现。
    – (Java 8: default and static methods)
    ➢ 不相关的类可以实现(implement)同一个接口, 同一个类可以实现多个不相关的接口。
    
  • Inner Classes

    ➢ 允许一个类的定义在另一个类/方法里
    ➢ 集中使用某些共同特性 → GUI event handlers
    
  • Arrays

    ➢ An array associates numerical indices to objects – most efficient choice
    ➢ Arrays in Java are objects which belongs to class Array.
    ➢ Array objects implements only static arrays
    ➢ Java follows strict bound checking for referencing array elements.
    ➢ Array elements can be referenced from 0 to length-1.
    ➢ Java also follows strict type checking for Array elements.
    ➢ length is the attribute of each array which can be referenced by arrayreference.length
    
  • Collections Of Objects

    • An array associates numerical indices toobjects

      • A Collection holds single elements, anda Map holds associated pairs

      • Like an array, a List also associates numerical indices to objects

      – Use an ArrayList if you’re doing a lot of random accesses

      – but a LinkedList if you will be doing a lot of insertions and removals in the middle of the list

      • The behavior of queues, deques, and stacks can be provided via the LinkedList

      • A Map is a way to associate not numbers, but objects with other objects

      • HashMap is focused on rapid access

      • TreeMap keeps its keys in sorted order, and thus is not as fast as a HashMap.

      • – A LinkedHashMap keeps its elements in insertion order, but may also reorder them with its LRUalgorithm

      • A Set only accepts one of each type ofobject.

      • HashSets provide maximally fast lookups

      • TreeSets keep the elements in sorted order

      • LinkedHashSets keep elements in insertion order

  • IO

    ➢ Stream
    – 输入流只能读不能写,输出流只能写不能读;
    – 程序通过输入流读入数据,输出流写数据;
    
    ➢ I/O is hard
      – deals with real world beyond programmers control 
      – Output easier than input (programmer knows more) 
        – System.out.println() is straightforward
      – Juno Terminal wraps hard to use System.in
    ➢ java.io package provides lots of useful classes
    ➢ I/O programs may throw many Exceptions
    ➢ Even good tools are hard to use when materials are recalcitrant
    ➢ Count on borrowing from code that works
    
  • NIO

     Useful and long awaited addition to Java
     New I/O has been widely hailed as an important step forward in getting serious performance out of the Java platform.
     Besides raw performance, it provides the most critical I/O and networking functionalities that were absent in earlier versions of Java.
    

补充:

  • .next()

    • random.nextInt(int bound )

      int x = rd.nextInt(36) + 1;  //  Random rd = new Random(); 
      

    • iterator

     List<String> list = new ArrayList<>();
            Iterator iterator = list.iterator();
            while (iterator.hasNext())  // hasNext()
                System.out.println(iterator.next());    // next()
    

    • 数据库resultSet.next()

      while (resultSet.next()) {
                  System.out.println(resultSet.getInt(1));
                  System.out.println(resultSet.getString(2));
              }
      

  • keyword: 不包含sizeof、status

  • FileOutPutStream

     public static void main(String[] args) {
            try {
                String s = "ABCDE";
                byte b[] = s.getBytes();
                FileOutputStream file = new FileOutputStream("test.txt",true);
                file.write(b);
                file.close();
            }catch (IOException e)
            {
                System.out.println(e.toString());
            }
        }
    

  • BufferedReader、FileReader、PrintWriter、FileWriter

     public static void main(String[] args)
        {
            File file = new File("./src/Exam/in.txt");
            File file1 = new File("./src/Exam/out.txt");
            System.out.println(file.exists());
            try (BufferedReader br = new BufferedReader(new FileReader(file));    // 
                 PrintWriter pw = new PrintWriter(new FileWriter(file1)))
            {
                int i = 0;
                String line;
                while ((line = br.readLine()) != null)      // br.readLine()
                {
                    pw.println("line " + (++i) + "=" + line);  // pw.println()
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    

 new ObjectOutputStream(new FileOutputStream(“file.txt”))

DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("something") // 网络编程
     
    
DataInputStream in = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());

 new BufferedReader(new FilerReader(“file.txt”));     
 new BufferedReader(new InputStreamReader(System.in)); 
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,491评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,856评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,745评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,196评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,073评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,112评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,531评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,215评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,485评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,578评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,356评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,215评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,583评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,898评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,497评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,697评论 2 335

推荐阅读更多精彩内容