Java 教程筆記-學習Java語言

學習Java語言

面向對象編程概念

核心概念:對象,消息,類和繼承
這一節會介紹 對象,類,繼承,接口和包

What Is an Object?
An object is a software bundle of related state and behavior.
對象是相關屬性和行為的軟件集合。
將不同的實物對象成不同的對象,有以下好處

  • 模塊化
  • 信息隱藏
  • 代碼復用
  • 擴展性和易調試

What Is a Class?
A class is a blueprint or prototype from which objects are created.
類是創建的對象的藍圖或原型。

What Is Inheritance?
Inheritance provides a powerful and natural mechanism for organizing and structuring your software.
繼承提供了一種強大且自然的機制來組織/構建程序。
面向對象編程允許從其他類繼承公共有用的屬性和行為。

A hierarchy of bicycle classes.

使用 extends關鍵字

class MountainBike extends Bicycle {

    // new fields and methods defining 
    // a mountain bike would go here

}

What Is an Interface?
An interface is a contract between a class and the outside world.
接口是類和外部世界的約定。當一個類實現接口,他承諾提供接口發布的行為。
定義接口:

interface Bicycle {

    //  wheel revolutions per minute
    void changeCadence(int newValue);

    void changeGear(int newValue);

    void speedUp(int increment);

    void applyBrakes(int decrement);
}

實現接口,使用關鍵字implements

class ACMEBicycle implements Bicycle {

    int cadence = 0;
    int speed = 0;
    int gear = 1;

   // The compiler will now require that methods
   // changeCadence, changeGear, speedUp, and applyBrakes
   // all be implemented. Compilation will fail if those
   // methods are missing from this class.

    void changeCadence(int newValue) {
         cadence = newValue;
    }

    void changeGear(int newValue) {
         gear = newValue;
    }

    void speedUp(int increment) {
         speed = speed + increment;   
    }

    void applyBrakes(int decrement) {
         speed = speed - decrement;
    }

    void printStates() {
         System.out.println("cadence:" +
             cadence + " speed:" + 
             speed + " gear:" + gear);
    }
}

What Is a Package?
A package is a namespace for organizing classes and interfaces in a logical manner.
包是以合理的方式來組織類和接口的一個命名空間。
把程序放到包里可以使得大項目易于管理。

語言基礎

Java語言的基礎特征:變量,數組,數據類型,操作符和控制流

Variables

Java 對象把屬性保存在域中:

int cadence = 0;
int speed = 0;
int gear = 1;

"field" and "variable" 這兩個概念是一樣的。

Java 語言中有下列幾種變量

  • 實例變量(Non-Staic Fields)
  • 類變量(Static Fields)
  • 本地變量: 臨時變量
  • 參數變量

命名規則

  • 變量名是大小寫敏感的case-sensitive,字母,數字,美元符號""和下劃線"_",長度沒有限制,開頭不能是數字。正常開頭都是字母,而不用''和'_'. 并且正常都不使用,只有自動生成的名字中有
  • 使用全詞來命名,而不是選擇縮寫。
  • 不能使用關鍵字來命名
  • 駝峰命名法
  • 常量命名為大寫,static final int NUM_GEARS = 6; 為了方便,其他地方一般不使用下劃線來命名。

Operators

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ? :
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Expressions, Statements, and Blocks

  • 表達式
    表達式是由變量,操作符和方法調用評估得到一個值。
    表達式返回值的數據類型取決于表達式中的元素:
int cadence = 0;

表達式 cadence = 0 返回的類型就是int.

表達式支持混合運算:
1 * 2 * 3 / 4
為了避免產生歧義和錯誤,建議用小括號

x + y / 100  //有歧義
(x + y) / 100
x + (y / 100)
  • 語句
    Java 語句大致跟自然語言的句子相同。
    語句形成表達式完整的單元。
    下列幾種表達式可以組成語句,并且用分號';'結束:
    1. 賦值表達式
    2. 自增/自減操作
    3. 方法調用
    4. 對象創建表達式
// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
Bicycle myBike = new Bicycle();

還有另外兩種語句
5. 聲明語句
6. 控制流

//declaration statement
double aValue = 8933.234;

//the decision-making statements 
if-then, if-then-else, switch,
//the looping statements 
for, while, do-while
//the branching statements 
break, continue, return

  • 塊是0條或多條語句的組合,用大括號圈起來。
class BlockDemo {
     public static void main(String[] args) {
          boolean condition = true;
          if (condition) { // begin block 1
               System.out.println("Condition is true.");
          } // end block one
          else { // begin block 2
               System.out.println("Condition is false.");
          } // end block 2
     }
}

Control Flow Statements

  • 選擇語句
if-then, if-then-else, switch
  • 循環語句
for, while, do-while
  • 分支語句
break, continue, return

類和對象

創建對象,使用對象

剖析類,以及怎樣聲明屬性,方法和構成器

public class Bicycle {
        
    // the Bicycle class has
    // three fields
    public int cadence;
    public int gear;
    public int speed;
        
    // the Bicycle class has
    // one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }
        
    // the Bicycle class has
    // four methods
    public void setCadence(int newValue) {
        cadence = newValue;
    }
        
    public void setGear(int newValue) {
        gear = newValue;
    }
        
    public void applyBrake(int decrement) {
        speed -= decrement;
    }
        
    public void speedUp(int increment) {
        speed += increment;
    }
        
}

幾種變量

  • Member variables in a class—these are called fields.
  • Variables in a method or block of code—these are called local variables.
  • Variables in method declarations—these are called parameters.

變量聲明:

  1. 0個或多個修飾符,例如public或private
  2. 類型
  3. 變量名
public int cadence;

權限修飾符:
public > protect > default > private

定義方法:

Here is an example of a typical method declaration:

public double calculateAnswer(double wingSpan, int numberOfEngines,
                              double length, double grossTons) {
    //do the calculation here
}

返回類型 方法名 括號( 參數 ) { 方法體 }

方法命名:駝峰命名法

run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty

重載方法:
通過不同的參數(類型,個數)來區別:

public class DataArtist {
    ...
    public void draw(String s) {
        ...
    }
    public void draw(int i) {
        ...
    }
    public void draw(double f) {
        ...
    }
    public void draw(int i, double f) {
        ...
    }
}

構造器:
A class contains constructors that are invoked to create objects from the class blueprint.
類調用構造器來創建對象。
構造器的聲明和方法聲明類似,有兩點不同:

  1. 使用類名作方法名
  2. 沒有返回類型
public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

調用構造器來創建對象,用new操作符

Bicycle myBike = new Bicycle(30, 0, 8);

一個類可以有多個構造器,他們之間的參數不同。
代碼沒有顯示聲明構造器的話,會有一個默認的無參構造器。

傳遞參數:
可以向方法或構造器傳遞參數。
參數的數量沒有限制
Java中的參數傳遞都是值傳遞,基本類型和引用類型有點區別:

public class PassPrimitiveByValue {
    public static void main(String[] args) {
        int x = 3;
        // invoke passMethod() with 
        // x as argument
        passMethod(x);
           
        // print x to see if its 
        // value has changed
        System.out.println("After invoking passMethod, x = " + x);  //這里x沒有被修改
    }    
    // change parameter in passMethod()
    public static void passMethod(int p) {
        p = 10;
    }
}

執行結果是:

After invoking passMethod, x = 3

基本變量傳遞參數時,方法內對參數的修改只在本地生效,不會影響外層的值。

package helloworldapp;

/**
 * @author linyk001
 * @date 2018/08/02
 */
public class Circle {
    int x;
    int y;

    public Circle(int xx, int yy) {
        x = xx;
        y = yy;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    @Override
    public String toString() {
        return "Circle [x=" + x + ", y=" + y + "]";
    }

    public void moveCircle(Circle circle, int deltaX, int deltaY) {
        // code to move origin of circle to x+deltaX, y+deltaY
        // circle指向的對象唄修改,外層的對象也跟著被修改,變成(27,62)
        circle.setX(circle.getX() + deltaX);
        circle.setY(circle.getY() + deltaY);
        System.out.println(circle);
        // code to assign a new reference to circle
        // 這里重新將circle變量指向新的對象(0,0),外層的circle依然是指向原來的對象(27,62)
        // 外層的circle指向的對象不會被修改,不會指向其他對象,但是對象的屬性值可以被修改。
        circle = new Circle(0, 0);
        System.out.println(circle);
    }

    public static void main(String[] args) {
        Circle myCircle = new Circle(4, 6);
        System.out.println(myCircle);

        moveCircle(myCircle, 23, 56);

        System.out.println(myCircle); //這里myCircle對象以及被修改了

    }
}/**Output
Circle [x=4, y=6]
Circle [x=27, y=62]
Circle [x=0, y=0]
Circle [x=27, y=62]
*///~

這里的值傳遞,指的是引用的值,外層的circle指向的對象不會被修改,不會指向其他對象,但是對象的屬性值可以被修改。

對象

As you know, a class provides the blueprint for objects; you create an object from a class.

Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

創建對象的語句有三個部分:

  • 聲明:類型+對象名 Point originOne
  • 實例化:new關鍵字是用來創建對象的Java操作符
  • 初始化:new調用構造器來初始化對象 Point(23, 94)

使用對象:

objectReference.fieldName
objectReference.methodName(argumentList)
objectReference.methodName();

垃圾收集器:

The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.

當對象不再被使用時,Java 運行環境會刪除它。這個過程叫做垃圾回收。

An object is eligible for garbage collection when there are no more references to that object.References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null.

當沒有應用指向對象的時候,它就是滿足垃圾回收要求的。當變量離開作用域時,它的引用就會被刪除。或者可以通過將變量賦值為null來刪除引用。

更多關于類

這一節是關于類依賴于使用對象引用和.操作符:

  • 返回值
    方法返回的三種情況:
    1. 所有語句正常執行結束
    2. return 語句
    3. 拋出異常

  • this 關鍵字
    this關鍵字指向當前對象

public class Point {
    public int x = 0;
    public int y = 0;
        
    //constructor
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}
public class Rectangle {
    private int x, y;
    private int width, height;
        
    public Rectangle() {
        this(0, 0, 1, 1);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}
  • 訪問控制
    public > protect > default > private
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
  • static 類變量和類方法
  1. 類變量

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables.

當創建類的多個對象時,每個對象實例都有各自的實例變量。如果在變量前面加上static關鍵字,這個變量就是類變量,是跟類關聯在一起,而不是對象實例。

public class Bicycle {
        
    private int cadence;
    private int gear;
    private int speed;
        
    // add an instance variable for the object ID
    private int id;
    
    // add a class variable for the
    // number of Bicycle objects instantiated
    private static int numberOfBicycles = 0;
        ...
}

上面的numberOfBicycles就是類變量 class variables or static fields.
2. 類方法

Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args)

類方法可以直接用類名來調用,不需要先創建對象實例。也可以跟普通方法調用一樣,使用 instanceName.methodName(args). 不過不推薦,因為這樣就不能將類方法和普通方法區分開了。

類方法的常見用法就是用來訪問類變量(靜態域).

訪問注意:

  • 實例方法可以直接訪問實例變量和實例方法;
  • 實例方法可以直接訪問類變量和類方法;
  • 類方法可以直接訪問類變量和類方法;
  • 類方法不可以訪問實例變量和實例方法-它們必須用一個對象引用才能訪問;
  • 類方法不能用this關鍵字,因為他不指向任何實例對象。
  1. 常量
    staticfinal關鍵字的組合可以用來定義常量。
    final 標識符表明這個域的值不能被修改。
static final double PI = 3.141592653589793;

如果想要改變PI的值,編譯報錯。

Note: If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.

如果一個基本類型或字符串類型被定義為常量,且編譯階段就知道常量的值,編譯器就會在用到這個常量的所有地方把它替換為具體的值。這個叫做編譯時常量。所以如果上面PI的值變成了3.975,那么就要重新編譯來獲取最新的值。

  • 初始化域
public class BedAndBreakfast {

   // initialize to 10
   public static int capacity = 10;

   // initialize to false
   private boolean full = false;
}

Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice. It is only necessary that they be declared and initialized before they are used.

沒有要求一定要在類定義的開頭聲明域,盡管這是最常見的用法。只需要滿足在使用域之前被初始化就可以。

Static Initialization Blocks 靜態初始化塊

static {
    // whatever code is needed for initialization goes here
}
  • 總結:創建,使用類和對象

A class declaration names the class and encloses the class body between braces.
類定義:命名類,并且用括號來圈起來類主體。

類主體包含域,方法和構造器。

  • 域: 屬性xinxi
  • 方法:實現行為
  • 構造器:初始化對象

類變量和類方法: static 關鍵字
實例變量和實例方法: 沒有用static關鍵字

嵌套類

Java允許在一個類里面再定義一個類,這個類就叫做嵌套類。

class OuterClass {
    ...
    static class StaticNestedClass {
        ...
    }
    class InnerClass {
        ...
    }
}

嵌套類是外部類的一個成員。
嵌套類分為兩個兩類:

  1. static 嵌套類不可以訪問外部類的其他成員。
  2. non-static 嵌套類(inner classes) 可以訪問外部類的其他成員

為什么使用嵌套類:

  • It is a way of logically grouping classes that are only used in one place:如果一個類僅僅被其他一個類訪問,那么可以將他們合理地嵌套在一起。
  • It increases encapsulation: 提高封裝特性。可以將內部類隱藏在外部類下
  • It can lead to more readable and maintainable code:提高代碼的易讀性和可維護性。

靜態內部類:

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

靜態內部類和它的外部類(或其他類)的實例成員的交互就像任何其他的頂層的類一樣。

//可以使用外部類的名字來訪問靜態內部類
OuterClass.StaticNestedClass

//例如,可以使用下面的語法來創建靜態內部類的對象
OuterClass.StaticNestedClass nestedObject =
     new OuterClass.StaticNestedClass();

普通內部類

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

類似實例方法和實例變量,內部類和外部類的一個實例對象相關聯,可以直接訪問這個實例對象的方法和域。而且,內部類是和實例對象相關聯,所以里面不能定義任何靜態成員。
一個內部類的實例只能存在域外部類的實例內。
要實例化內部類,必須先實例化外部類,然后用下面的語法來創建內部類:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

普通內部類 Inner classes 分為兩種:

  1. Local 本地內部類
  2. Anonymous 匿名內部類

內部類同樣可以使用private,public和protected.

Shadowing 隱藏

 package helloworldapp;

 /**
 * @author linyk001
 * @date 2018/08/02
 */
public class ShadowTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {
            System.out.println("x = " + x);
            System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);
    }
}/**Output:
x = 23
this.x = 1
ShadowTest.this.x = 0
*///~

序列化:
內部類的序列化是強烈勸阻的,包括本地內部類和匿名內部類。

Lambda表達式: 用來優美地實例化只有一個方法的類。
Lambda 表達式看上去更像是一個方法的聲明,可以把Lambda表達式當成匿名方法,一個沒有名字的方法。

Lambda表達式語法:

  • 包含在花括號內逗號分隔的正常參數。
  • 箭頭符號 ->
  • 主體,包含簡單的表達式或者語句塊

package helloworldapp;

 /**
 * @author linyk001
 * @date 2018/08/03
 */
public class Calculator {

    interface IntegerMath {
        int operation(int a, int b);   
    }

    public int operateBinary(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }

    public static void main(String... args) {

        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}/**Output:
40 + 2 = 42
20 - 10 = 10
*///~

方法operateBinary 對兩個整型操作數進行算術運算。運算方式是用接口IntegerMath聲明的。這個例子用Lambda表達式定義了兩種操作,addition 和 subtraction。

如果一個Lambda表達式的目標類型和攜帶參數都是可序列化的,你可以序列化這個Lambda表達式。然而,就像匿名類,強烈建議別瞎搗騰去序列化Lambda表達式。

枚舉類型

枚舉類型:是一個允許定義和使用常數集合的特殊類。

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

枚舉類型有個方法 values() 可以返回包含所有值的數組,并且按照聲明的順序。

for(Day d : Day.values()) {
        //...
}
 package helloworldapp;

 /**
 * @author linyk001
 * @date 2018/08/03
 */
 public enum Planet {
     MERCURY (3.303e+23, 2.4397e6),
     VENUS   (4.869e+24, 6.0518e6),
     EARTH   (5.976e+24, 6.37814e6),
     MARS    (6.421e+23, 3.3972e6),
     JUPITER (1.9e+27,   7.1492e7),
     SATURN  (5.688e+26, 6.0268e7),
     URANUS  (8.686e+25, 2.5559e7),
     NEPTUNE (1.024e+26, 2.4746e7);

     private final double mass;   // in kilograms
     private final double radius; // in meters
     Planet(double mass, double radius) {
         this.mass = mass;
         this.radius = radius;
     }
     private double mass() { return mass; }
     private double radius() { return radius; }

     // universal gravitational constant  (m3 kg-1 s-2)
     public static final double G = 6.67300E-11;

     double surfaceGravity() {
         return G * mass / (radius * radius);
     }
     double surfaceWeight(double otherMass) {
         return otherMass * surfaceGravity();
     }
     public static void main(String[] args) {
         if (args.length != 1) {
             System.err.println("Usage: java Planet <earth_weight>");
             System.exit(-1);
         }
         double earthWeight = Double.parseDouble(args[0]);
         double mass = earthWeight/EARTH.surfaceGravity();
         for (Planet p : Planet.values())
            System.out.printf("Your weight on %s is %f%n",
                              p, p.surfaceWeight(mass));
     }
}/** Output:傳入的參數是111時
Your weight on MERCURY is 41.931095
Your weight on VENUS is 100.454900
Your weight on EARTH is 111.000000
Your weight on MARS is 42.039827
Your weight on JUPITER is 280.891885
Your weight on SATURN is 118.327725
Your weight on URANUS is 100.469119
Your weight on NEPTUNE is 126.354416
*/// ~

注解

參考譯文
注解是一種元數據的形式,為編譯器提供信息。
注解不是程序本身,僅提供程序相關的信息,注解對它們所注釋的代碼沒有直接的影響。
這里介紹在哪里以及怎樣高效的在程序中使用注解。

注解的用途:

  • Information for the compiler:為編譯器提供信息來檢測錯誤或者抑制警告。
  • Compile-time and deployment-time processing: 編譯時和發布時處理,軟件工具可以處理注解信息來生成代碼,XML文件等等。
  • Runtime processing,運行時處理,一些注解可以在運行時進行檢查。
注解基礎

注解的格式:
符號@告訴編譯器這接下來的是一個注解。

@Entity

@Override
void mySuperMethod() { ... }


@Author(
   name = "Benjamin Franklin",
   date = "3/27/2003"
)
class MyClass() { ... }
or

@SuppressWarnings(value = "unchecked")
void myMethod() { ... }

//如果只有一個元素叫做value,那這個名字可以被省略
@SuppressWarnings("unchecked")
void myMethod() { ... }


@Author(name = "Jane Doe")
@Author(name = "John Smith")
class MyClass { ... }

可以使用注解的地方:
注解可以用在聲明:聲明類,域,方法和其他程序元素。當注解用在聲明時,一般是單獨一行。

Java SE8 發布后,注解可以用在類型:

//Class instance creation expression: 創建類的實例
 new @Interned MyObject();

//Type cast:類型強制轉換
myString = (@NonNull String) str;

//implements clause:實現子句
class UnmodifiableList<T> implements
        @Readonly List<@Readonly T> { ... }

//Thrown exception declaration:拋異常聲明
void monitorTemperature() throws
        @Critical TemperatureException { ... }

聲明一個注解類型

許多注解用來替換代碼中的注釋。
一般類中的注釋信息:

public class Generation3List extends Generation2List {

   // Author: John Doe
   // Date: 3/17/2002
   // Current revision: 6
   // Last modified: 4/12/2004
   // By: Jane Doe
   // Reviewers: Alice, Bill, Cindy

   // class code goes here

}

要用注解來加上同樣的元數據,我們首先需要定義一個注解類型:

@interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

定義注解的方式有點類似定義接口,使用了關鍵字interface和前綴@符號,注解是屬于接口的一種。
定義好注解后,就可以使用注解了:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {

// class code goes here

}

Note: To make the information in @ClassPreamble appear in Javadoc-generated documentation, you must annotate the @ClassPreamble definition with the @Documented annotation:

為了@ClassPreamble的信息可以出現在javadoc文檔生成中,需要在定義中加上@Documented注解

// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

   // Annotation element definitions

}

預定義注解類型

一系列的注解類型在Java SE API中預定義了。一些注解類型被用在Java編譯器,一些被用在其他注解上。

Java語言中用到的注解

java.lang中預定義的注解類型是:

  • @Deprecated:棄用
    表示已經被棄用,當程序使用了@Deprecated注解標注的方法/類/域時,編譯器會發出警告。
  • @Override: 覆蓋
    告訴編譯器這個元素是覆蓋父類的一個元素聲明

  • @SuppressWarnings:抑制警告
    告訴編譯器抑制原本會產生的特定的警告。

// use a deprecated method and tell 
   // compiler not to generate a warning
   @SuppressWarnings("deprecation")
    void useDeprecatedMethod() {
        // deprecation warning
        // - suppressed
        objectOne.deprecatedMethod();
    }

上面例子中,調用了一個被棄用的方法,正常編譯器會提示警告,但是加了@SuppressWarning后,這個警告就被抑制了。
抑制多種警告信息:

@SuppressWarnings({"unchecked", "deprecation"})
  • @SafeVarargs 安全參數
    運用在方法或構造器上,表明代碼不會對參數進行潛在的不安全的操作。

  • @FunctionalInterface 函數式接口
    表示聲明的類型是Java SE 8中的函數式接口

被其他注解應用的注解

被其他注解應用的注解成為元注解
這里有一些元注解定義在java.lang.annotation

  • @Retention 保留注解
    表明標記的注解是怎么保存的:

    1. RetentionPolicy.SOURCE 只保留在源碼中,編譯器會忽略它
    2. RetentionPolicy.CLASS 編譯時被編譯器保留,但是被JVM忽略
    3. RetentionPolicy.RUNTIME 被JVM保留所以能在運行時環境使用
  • @Documented Java 文檔
    表明被標記的注解要被javadoc工具記錄。 Javadoc tools page.

  • @Target 目標
    限制被標記的注解能被哪種Java 元素應用。

    1. ElementType.ANNOTATION_TYPE can be applied to an annotation type.
    2. ElementType.CONSTRUCTOR can be applied to a constructor.
    3. ElementType.FIELD can be applied to a field or property.
    4. ElementType.LOCAL_VARIABLE can be applied to a local variable.
    5. ElementType.METHOD can be applied to a method-level annotation.
    6. ElementType.PACKAGE can be applied to a package declaration.
    7. ElementType.PARAMETER can be applied to the parameters of a method.
    8. ElementType.TYPE can be applied to any element of a class.
  • @Inherited 繼承
    表示被標記的注解類型可以從父類中繼承。這個注解只用在類的聲明。

  • @Repeatable 可重復的
    Java SE8 中@Repeatable注解表明被標記的注解可以被應用多次在同一個聲明或類型使用上。

Type注解和插件

在Java 8之前,注解僅僅只能在聲明(declarations)時使用。在Java 8,注解可以在任何 type use。這就是說,注解可以應用在任何你使用type的地方。例如,class實例的創建表達式(new),類型轉換(casts),implements子句,throws子句。這種注解被稱為type annotation。更多例子,可以參考上面的基礎知識(Annotations Basics)。
Type annotation是為了提高Java程序的強類型檢查功能而誕生的。Java 8并沒有提供一個類型檢查框架(type checking framework),但卻允許你自己寫(或者down)一個類型檢查框架作為Java編譯器的插件使用。

舉個例子,你想確保你程序里的某些變量永遠不會被賦值為null;你想避免產生NullPointerException。你可以自己寫個插件來檢查。你只需要修改你的代碼,把特定變量加上標識不能用null賦值的注解。這個變量的聲明可能看起來像這樣:

@NonNull String str;
重復注解

Java SE 8 開始,可以使用重復注解

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }

接口和繼承

接口是什么,為什么使用接口,怎樣使用接口
從基類繼承,生成一個導出類。子類和父類的關系

所有的類都是繼承自Obeject

Numbers和Strings

Number 和 String 類的使用,以及格式化輸出

泛型

泛型是Java語言中一個強大的特性,提升了代碼的類型安全,使得代碼bug能在編譯階段檢測得到

包能夠幫助你組織構造生成的類以及其他類之間的關系。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容