小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

ORACLE官網(wǎng)JAVA學(xué)習(xí)文檔

 印度阿三17 2019-08-15

Trails Covering the Basics

? 1 Getting Started 1.1 The Java Technology Phenomenon 1.1.1 About the Java Technology? ? The Java Programming Language ? ? ?? ?

Figure 1?an overview of the software development process

? ? java文件以.java作為后綴 源文件被javac compiler編譯為.class 文件 .class文件中是字接碼 ? ?? ? Figure 2?java跨平臺的原因 ? 在不同系統(tǒng)中安裝java vm, .class 文件可以在不同平臺上運作。 ? The Java Platform ? 平臺是軟硬件運行的地方 但是java平臺不同于其他的平臺 ? Java平臺僅僅只是軟件,他運行在基于其他硬件的平臺之上(Figure 3) ? ?? ?

Figure 3 java平臺的兩個組件

?

?

? ? 1.1.2 What Can Java Technology do? 開發(fā)工具: Javac 編譯器 java 啟動器 javadoc 文檔工具 ? API: 提供給JAVA核心的編程功能 1.1.3 How Will Java Technology change my life? Write once, run anywhere? ? ? Write better code: 垃圾自動回收避免內(nèi)存泄漏 ? ? 1.2 The "Hello World" Application 這一部分使用netbean和不同的操作系統(tǒng)環(huán)境編寫“Hello World” 略 ? ? 1.3 A Closer Look at "Hello World" 注釋: /* text */ /** documentation */ //text? ? The main method? public static void main(Stirng[] args) args argv? ? 初始化運行時的參數(shù) ? ?
java MyApp arg1 arg2
? ? 1.4 Common Problems(and Their Solutions) 一些初學(xué)者常見的錯誤 https://docs.oracle.com/javase/tutorial/getStarted/problems/index.html Updating the PATH Environment Variable: https://docs.oracle.com/javase/8/docs/technotes/guides/install/windows_jdk_install.html#BABGDJFH ? ? ? 2. Learning the Java Language? 2.1 Object-Oriented Programming Concepts? 2.1.1 What is an Object? ?? ? ? ? 萬物皆對象 軟件隊形和現(xiàn)實對象相似 ? 他們都由狀態(tài)和行為組成 state & behaviour ? state->variables behaviour->methods ? 2.1.2 What is a Class? ? bicycle is an instance of the class of the objects ? A class is the blueprint from which individual objects are created ? 類是對象的實例 類是對象的藍(lán)圖 ? ?
class Bicycle{
int cadence=0;
int speed=0;
int gear=1;

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

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

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

void applyBrakes(int increment)
{

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

}
? ? ? ? ? ?
class BicycleDemo{
public static void main(Stirng[] args)
{
Bicycle bicycle1= new Bicycle();
Bicycle bicycle2= new Bicycle();

bicycle1.changeCadence(50);
bicycle1.speedUp(10);
bicycle1.printStates();

bicycle2.changeCadence(60);
bicycle2.changeGear(20);
bicycle2.speedUp(10);
bicycle2.printStates();
}
}
? ? ? 2.1.3 What is Inheritance?

??

? ? ?
class MountainBike extends Bicycle
{
//new fieds and methods defining
//a mountaion bike would go there
}
? ? 2.1.4 What is an Interface? ? 接口是一組具有空體的相關(guān)方法。以bicycle為例: ? ?
interface Bicycle
{
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);

}
? ? ? ?
class ACMBicycle implements Bicycle
{
int cadence=0;
int speed=0;
int gear=1;

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 printSatas()
{
System.out.println("cadence" cadence "speed" speed "gear" gear)
}
}
? ? 接口相當(dāng)于一個契約,在類與外部世界之間。 如果類需要實現(xiàn)一個接口,接口說定義的方法必須出現(xiàn)在源文件中,才能編譯成功。 ? ? ? ? 2.1.5 What is a Package? ? ? 包是組織一系列相關(guān)類和接口的命名空間 ? ? ? Application Programming Interface ? https://docs.oracle.com/javase/8/docs/api/index.html ? 2.1.6 Questions and Exercises: Object-Oriented Programming Concepts Exercise 2 ? Real-world objects contain?state?and?behaviour A software object's state is stored in?fields(variables) A softeare object's behaviour is exposed through?methods Hiding internal data from outside world, and accessing it only through publicly exposed methods is known as?data encapsulation. A blueprint for a software object is called a?class Common behaviour can be defined in a?superclass?and inherited into a?subclass?using the?extends?keyword A collection of methods wiht no implementment is called an?interface. A namespace that orgnaises classes and interfaces by functionality is called?package The term API stands for?Application Programming Interface ? ? 2.2 Language Basics 2.2.1 Variables 2.2.1.1 Primitive Data Types ?
byte 8-bit
? ? ? ? Default value ?
Data type? Default value(for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String(or any object) null
boolean false
? ? Floating-Point Literals
float? 以F或者f結(jié)尾
double 以D或者d結(jié)尾
? ? Character and String Literals
char single quote
String double quote
? ? ? ? ? ? ? ? 2.2.1.2 Arrays ? Declaring a Variable to Refer to an Array ?
byte[] anArrayOfBytes;
short[] anArrayOfShorts;
int[] anArrayOfInts;
long[] anArratOfLongs;
? ? 也可以將括號放在最后 ?
float anArrayOfFloats[]
? ? ? ? Creating,Initializing,and Accessing an Array ? 為整數(shù)創(chuàng)造數(shù)組 ? initizlizing
anArray=new int[10]
? 另外一種創(chuàng)造和初始化數(shù)組的方式 ? ?
int[] anArray=
{
100,20,40,50,
500,12,12,14
}
? ? Coping Arrays ? 這個功能是從src開始復(fù)制,復(fù)制的初始位置是srcPro
public static void arrraycopy(Object src, int srcPro
Object dest, int destPos, int length
)
? ? ?
public class Array {
public static void main(String[] argv)
{
char[] copyFrom={'d','e','f','a','b','c','d'};
char[] copyTo=new char[4];

System.arraycopy(copyFrom,3,copyTo,0,4);
System.out.println(new String(copyTo));

}
}
? The conditional operators && Conditional - And || Conditional - OR ? ? ? Array Manipulations ? ?
class ArrayCopyDemo
{
public static void main(String[] args)
{
char[] copyForm={'a','b','c','d','e'}
char[] copyTo= java.util.Arrays.copyOfArrays(copyForm,1,4);
System.out.println(new String(copyTo));
}
}
  • Searching an array for a specific value to get the index at which it is placed (the?
binarySearch
  • method).
  • Comparing two arrays to determine if they are equal or not (the?
equals
  • method).
  • Filling an array to place a specific value at each index (the?
fill
  • method).
  • Sorting an array into ascending order. This can be done either sequentially, using the?
sort
  • method, or concurrently, using the?
parallelSort
  • method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.
? ? 2.2.1.3 Summary of Variables instance variables(non-static fields) class variables(static fields) ? 2.2.1.4 Questiosn and Exercises:Variables The term "instance variable" is another name for?non-static field The term "class variable" is another name for?static field A local variable stores temporary state; it is declared inside a?method A variable declared within the opening and closing parenthesis of a method signature is called a?parameter What are the eight primitive data types supported by the Java programming language? byte short int long float double boolean char Character strings are represented by the class? java.lang.String An?array?is a container object that holds a fixed number of values of a single type. ? 2.2.2 Operators 2.2.2.1 Assignment,Arithmetic,and Unary Operators The only difference is that the prefix version ( result) evaluates to the incremented value, whereas the postfix version (result ) evaluates to the original value i相對效率更好 i 是先把i的值拿來用,然后在自增1 i是想把i自增1然后拿來用 ? The arthimetric operators
Operator? Description
Additive
- Subtraction operator
* Multiplication operator
/ Division operator?
% Remainder operator?
? ? ? The unary operators ? ?
Operator Description
Unary plus operator
- Unary minus operator?
Increment operator?
-- Decrement operator?
! Logical complement operator
? 2.2.2.2 Equality,Relational, and Conditional Operators ? The Equality and Relational Operators
== equal to?
!= not equal to?
> gearter than
>= greater than or equal to
< less than
<=? less than or equal to?
? ? ?
public class Array {
public static void main(String[] argv)
{
int value1=1;
int value2=2;
if(value1==value2)
{
System.out.println("value1==value2");
}
if(value1!=value2)
{
System.out.println("value1!=value2")
}
if(value1>value2)
{
System.out.println("value1>vluae2");
}
if(value1<value2)
{
System.out.println("value1<value2");
}
}
}
? The Conditional Operators ? ? ? ? ?
public class ConditionalDemo1 {
public static void main(String[] argv)
{
int value1 = 1;
int value2 = 2;
if((value1==1)&&(value2==2))
{
System.out.println("value1 is 1 AND value2 is 2");
}
if((value1==1)||(value2==2))
{
System.out.println("value1 is 1 OR value2 is 1");
}
}
}
? ? Ternary operator if someCondition is true , assign the value of value1 to result. Otherwise assign the value of value2 to result ? ? ?
class ConditionalDemo2 {

public static void main(String[] args){
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;

System.out.println(result);
}
}
? The Type Comparison Operator instanceof ? ? instanceof 使用來使用判斷一個實例的class, subclass 和一個class 用來實現(xiàn)一個特定的接口 ? ? ?
public class InstanceofDemo {
public static void main(String[] args)
{
Parent parent1 = new Parent();
Child child = new Child();
System.out.println("parent1 instanceof Parent " (parent1 instanceof Parent));
System.out.println("parent1 instanceof Child " (child instanceof Child));
System.out.println("parent1 instanceof MyInterface " (parent1 instanceof MyInterface));
System.out.println("child instanceof Parent " (child instanceof Parent));
System.out.println("child instanceof Child " (child instanceof Child));
System.out.println("child instanceof MyInterface " (child instanceof MyInterface));

}
}

class Parent{}

class Child extends Parent implements MyInterface{}

interface MyInterface{}
? 2.2.2.3 Bitwise and Bit Shift Operators
bitwise & bitwise AND operation
bitwise ^ exclusive OR operation 位互斥或操作符
bitwise | inclusive OR operation 位包換或操作符
?
class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
// prints "2"
System.out.println(val & bitmask);
}
}
? ? 2.2.2.4 Summary of Operators Simple Assignment Operator ? ?
= Simple assignment operator
? ? ? ? Arthimetirc Operators ?
Additive operator(also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator?
% Remainder operator
? ? ? Unary Operators ? ?
Unary plus operator;indicates positive value
- Unary minus operator;negates an exprssion
Increment operator
? ? Equality and Relational Operators ?
== Equal to?
!= Not equal to?
> Greater than
>=? Greater than or equal to?
< Less than
<=? Less than or equal to
? ? Conditional Operators ?
&& Conditional-And
|| Conditional-OR
?: Ternary
? ? Type Comparison Operator ?
instanceof? Compares an object to a specified type
? ? ? Bitwise and Bit Shift Operators ?
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND?
^ Bitwise exclusive OR
| Bitwise incluseive OR
? ? ? ? 2.2.3 Expressions, Statements, and Blocks ? ? Expression An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value ? Statements Statements are roughly equivalent to sentences in natural languages ? Block block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.? ? ? ? ? 2.2.4 Control Flow Statements 2.2.4.1 The if-then and if-then-else Statements The if-then Statement ? The if-then-else Statement ?
class IfElseDemo {
public static void main(String[] args) {

int testscore = 76;
char grade;

if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " grade);
}
}
一旦滿足一個條件,剩余條件就不會被執(zhí)行 ? ? 2.2.4.2 The switch Statement ? ?
public class SwithDemoFallThrough
{
public static void main(String[] args)
{
java.util.ArrayList<String> futureMonths = new java.util.ArrayList<String>();
int month = 8;
switch(month)
{
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9: futureMonths.add("September");
case 10: futureMonths.add("October");
case 11: futureMonths.add("November");
case 12: futureMonths.add("December");
break;
default: break;


}

if(futureMonths.isEmpty())
{
System.out.println("Invalid month number");
}
else
{
for(String monthName:futureMonths)
{
System.out.println(monthName);
}
}

}
}
? 2.2.4.3 The while and do-while Statements ?
while(expression)
{
statements
}
? 先執(zhí)行一次,再判斷 ? ?
do
{
statement(s)
}while(expression)
? ? 2.2.4.4 The for Statement ?
for(initilization;termination;increment)
{
statement(s)
}
? ? initilization:初始化表達(dá)式初始化循環(huán),它在循環(huán)開始執(zhí)行一次 termination:如果等于false,循環(huán)結(jié)束 increment: 每一次迭代后,increment 調(diào)用一次;可增,可減 ? ? more compact and easy to read ? ?
public class EnhancedForDemo {
public static void main(String[] args) {
int[] numbers={1,2,3,4,5,6,7,8};
for(int item: numbers)
{
System.out.println(item);
}
}
}
? ? ? 2.2.4.5 Branching Statements break 帶標(biāo)簽的break ? ? continue ? ?
public class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts=
{
{32, 87, 3, 589 },
{1, 1076, 2000, 8},
{622, 127, 77, 955}
};
int searchfor =12;
int i;
int j=0;
boolean foundIt= false;

search:for(i=0;i<arrayOfInts.length;i )
{
for(j=0;j<arrayOfInts[i].length;j )
{
if(arrayOfInts[i][j]==searchfor)
{
foundIt=true;
break search;
}
}
}

if(foundIt==true)
{
System.out.println("found it!");
}
else
{
System.out.println("not found it!");
}
}
}
? ? ? ? ? ? ? ? ?
public class ContinueWithLabelDemo
{
public static void main(String[] args)
{
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max=searchMe.length()-substring.length();

test:for(int i=0;i<=max;i )
{
int n=substring.length();


int j=i;
int k=0;

while(n-- !=0)
{
if(searchMe.charAt(j )!=substring.charAt(k ))
{
continue test;
}
}
if(foundIt=true)
{
break test;
}
}
if(foundIt)
{
System.out.println("found it");
}
else
{
System.out.println("Not found it");
}

}

}
? return? ? Questions and Exercises ? The most basic control flow statement supported by java programming language is the?if-then?statement ? The switch statements allows for any number of possible execution paths ? The statements is similiar to the while statement, but evaluates its expression at the botto, of the loop ? ? How do you write an infinite loop using the for statement? for( ; ; ) { } How do you write an infinite loop using the while statement? while(true) { } ? ? ? 2.2.4.6 Summary of Control Flow Statements 2.2.4.7 Questions and Exercises ? ? 2.3 Classes and Objects 2.3.1 Classes 2.3.1.1 Declaring Classes class declaration class body ?
class MyClass
{
//fields,constructor, and
//method declarations
}
? ? MyClass繼承于MySuperClass 實現(xiàn)接口YourInterface
class MyClass extends MySuperClass implements YourInterface
{
//field, constructor, and
//method declarations

}
? 2.3.1.2 Declaring Member Variables 三種不同的變量:
  • 類中的成員變量-叫做字段
  • 方法或者代碼中的變量叫本地變量
  • 字段聲明叫做參數(shù)

?

? ? fields的例子: ? ?
public int cadence
public int gear
public int speed
? ? Field declaration 由三個部分組成 修飾符: Zero or more modifiers 字段類型 The field's type 字段名字 The field's name ? Access Modifiers ? public: 字段可以訪問所有類 private: 字段僅能夠再類中訪問 ? ?
public class PrivateBicycle
{
private int cadence;
private int gear;
private int speed;

public PrivateBicycle(int startCadence, int startSpeed, int startGear)
{
gear = startGear;
speed = startSpeed;
cadence = startCadence;

}
public int getCadence()
{
return cadence;
}

public int getGear()
{
return gear;
}
public int getSpeed()
{
return speed;
}
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;
}
}
? 2.3.1.3 Defining Methods ?
  1. 修飾符 public , private
  2. 返回type
  3. 方法名
  4. 參數(shù)
  5. an exception list
  6. 方法體
? code conventation 方法名應(yīng)該是一個或者多個名字開始于小寫字母 緊接著名詞,形容詞 第二或者更往后的名次首字母應(yīng)該大寫 ? ? overloading ? 相同的方法名,不同的argument ? ?
public class DataArtist
{
public void draw(String s){}
public void draw(int i){}
public void draw(double f){}
public void draw(float f){}
}
? 2.3.1.4 Providing Constructors for Your Classes no-argument constructor 構(gòu)造器聲明就像方法聲明 ?
Bicycle yourBike = new Bicycle()
? 調(diào)用無參構(gòu)造方法 If another class cannot call a MyClass constructor, it cannot directly create MyClass objects ? 2.3.1.5 Passing Informaiton to a Method or a Constructor ?
public double computePayment(double loanAmt, double rate, double futureValue, int numPeriods)
{
double interest= rate/100.0;
double partial1= Math.pow((1 interest),-numPeriods);
double denominator = (1-partial1)/interest;
double answer = (-loanAmt/denominator)-((futureValue*partial1)/denominator);
return answer;

}
? Parameter Types ? 參數(shù)可以是原始數(shù)據(jù)類型,也可以是引用數(shù)據(jù)類型。 ? ?
public Polygon polygonFrom(Point[] corners)
{
//method body goes there
}
? ? Arbitrary Number of Arguments
 public Ploygon ploygonFrom(Point... corners)
{
int numberOfSides = corners.length;
double squareOfSide1,lengthOfSides
squareOfSide1 = (corners[1].x-corners[0].x)*(corners[1].x-corners[0]) (corners[1].y-corners[0].x)*(corners[1].y-corners[0].y)
lengthOfSides=Math.sqrt(squareOfSide1);

}
? ?
public PrintStream printf(Stirng format,Object... args)
? Passing Reference Data Type Arguments ? ? ? 2.3.2 Objects 2.3.2.1 Creating Object ? 類為對象提供藍(lán)圖 ? 從類中創(chuàng)造對象 ? ?
Point originOne = new Point(20,30);
? Declaration:??type and name Instantiation:?new 是創(chuàng)造對象的Java operator Initialization:?constructor用于初始化new object ? ?? ? ? ? ? ? 引用不一定分配一個variable ,也可以是一個表達(dá)式 ?
int height = new Rectangle().height;
? ? Initializing an Object ?? ? ? ?
Rectangle rectOne = new Rectangle(originOne,100,200)
? ?? 2.3.2.2 Using Objects ? Referencing an Object's Fields ? object reference? rectone.width ? ? expression int height = new Rectangle().length; ? ? Calling an Object's methods ? ?
new Rectangle(100,50).getArea()
? ? ? ? The Garbage Collector ? garbage collection?JAVA運行環(huán)境會自動刪除不需要使用的對象。 java進(jìn)行周期性的回收 ? 當(dāng)變量超出范圍時,在變量引用會被刪除。或者設(shè)置變量為special value null ? ? 2.3.3 More on Classes
  • Returning values from methods
  • The this key word
  • Class vs. instance members
  • Access control
2.3.3.1 Returning a Value from a Method java在三種情況下停止:
  1. 運行完所有方法
  2. 抵達(dá)return 語句
  3. 拋出異常
? ? 什么都不返回: return; ? Returning a Class or Interface ? ? ? ? 當(dāng)一個方法用類作為返回值時,返回對象的類型要么是子類,或者是確切類。 e.g: ? ?? 現(xiàn)在假設(shè)有一個方法返回Number ?
public Number returnANumber{
...
}
? 這個returnANumber可以返回ImaginaryNumber,但是不可以返回Object ? covariant return type You can override a method and define it to return a subclass of the original method, like this: ?
public ImaginaryNumber returnANumber() {
...
}
? 2.3.3.2 Using the this Keyworkd Using this with a Field ? Each argument to the constructor shadows one of the object's fields? ?
public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
? ? Using this with a Constructor ? 顯式構(gòu)造函數(shù)調(diào)用 ?
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;
}
...
}
? ? ? 2.3.3.3 Controlling Access to Members of a Class ? ? Package Two是Package One的子類 ?? ? Visibility ?? ? ? ? Access Levels ? ?? ? ? public 是所有包都可見; protected 是不同包非子類不可見; no modifie同包可見; private僅僅同類可見。 ? ? ? 2.3.3.4 Understanding Class Members Class Variables ? 靜態(tài)變量中,類變量可以通過類名直接訪問,也可以通過實例對象訪問,但是一般很少使用實例對象訪問。因為這無法表示他們是類變量。 ? Class Methods ?
public static int getNumberOfBicycles
{
return numberOfBicycles;
}
tips: ?
  • 實例方法可以直接訪問實例方法和實例變量
? ?
  • 實例方法可以直接訪問類變量和類方法;
? ?
  • 類方法可以直接訪問類方法和類變量;

?

  • 類方法不能直接訪問實例變量和實例方法,他們必須使用一個對象引用。也不能使用this關(guān)鍵字。因為沒有this所指引的實例。
? ? Constants ? ? ?
static final double PI = 3.141592653589793;
If the name is composed of more than one word, the words are separated by an underscore (_). ?

?

The Bicyle Class ?
public class Bicycle
{
public static void main(String[] args) {
System.out.println(Bicycle.getNumberOfBicycle());
}



private int cadence;
private int gear;
private static int numberOfBicycle=2;

public int getCadence() {
return cadence;
}

public void setCadence(int cadence) {
this.cadence = cadence;
}

public int getGear() {
return gear;
}

public void setGear(int gear) {
this.gear = gear;
}

public static int getNumberOfBicycle() {
return numberOfBicycle;
}

public static void setNumberOfBicycle(int numberOfBicycle) {

Bicycle.numberOfBicycle = numberOfBicycle;
}
}
? ? ? 2.3.3.5 Initializing Fields ? ?
public class BedAndBreakfast {
public static int capacity=10;
private boolean full=false;
}
? ? Static Initialization Blocks ? A static initialization block is a normal block of code enclosed in braces{}, and preceded by the static keyword ? ?
static
{
// whatever code is needed for initialization goes here
}
? ?
class Whatever
{
public static varType myVar=initializeClassVariable();

private static varType initializeClassVariable()
{
//initialization code goes here
}
}
? The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable. ? ? Initializing Instance Members ? ? Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword ? ? ?
{
// whatever code is needed for initialization goes here
}
? ? ?
class Whatever
{
private varType myVar=initializeInstanceVariable();
protected final varType initializeInstanceVariable()
{
// initialization code goes here
}
}
? ? ? ? ? 2.3.3.6 Summary of Creating and Using Classes and Objects 通過在類聲明中使用一個static keyword聲明類變量或者類方法。如果一個成員變量沒有聲明static,則隱示的作為成員變量。類變量可以被類實例和類名字訪問。 ? ? ? ? You can explicitly drop a reference by setting the variable holding the reference to null. ? ? 2.3.4 Nested Classes ? ? 嵌套類 static nested classes:?靜態(tài)嵌套類 non-static nested classes:inner classes:??內(nèi)部類?
public class OuterClass {
...
class NestedClass
{
...
}
}
? ? ?
class OuterClass
{
...
static class StaticNestedClass
{
...
}
class innerClass
{
...
}
}
? ? 非靜態(tài)類嵌套類可以訪問封閉類的其他成員變量,即使他們被聲明為私有 ? 靜態(tài)嵌套類不能訪問封閉類的其他成員 ? 嵌套類可以聲明為private ,public , protected,package private ? (請記住,外部類只能聲明為public or package private) ? ? ? ?
OuterClass.StaticNestedClass
? 創(chuàng)建一個靜態(tài)嵌套類對象 ?
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass
? ? 非靜態(tài)類(內(nèi)部類) ? ?
class OuterClass
{
...
class InnerClass
{
...
}

}
? ? ? 為了實例化內(nèi)部類,應(yīng)該先實例化外部類 ?
OuterClass.InnerClass innerObject=  outerObject.new InnerClass();
? ? ? Shadowing ? ?
public class ShowTest
{
public int x=0;
class FirstLevel
{
public int x=1;
void methodInFirstLevel
{
System.out.println(x);
System.out.println(this.x);
System.out.println(ShowTest.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
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 2.3.4.1 Inner Class Example ? ?
public class DataStructure {
//create an array
private final static int SIZE =15;
private int[] arrayOFInts = new int[SIZE];

public void printEven()
{
DataStructureIterator iterator = this.new EvenIterator();
while(iterator.hasNext())
{
System.out.println(iterator.next() " ");
}
System.out.println();
}

interface DataStructureIterator extends java.util.Iterator<Integer>{}

private class EvenIterator implements DataStructureIterator
{
private int nextIndex =0;

public boolean hasNext()
{
return (nextIndex<=SIZE-1);
}

public Integer next()
{
Integer retValue=Integer.valueOf(arrayOFInts[nextIndex]);

nextIndex =2;
return retValue;

}
}

public static void main(String[] args) {
DataStructure ds = new DataStructure();
ds.printEven();
}

}
The EvenIterator實現(xiàn)DataStructureIterator 接口 ? ? ? ? ? ? 2.3.4.2 Local Classes ? ? ? ? ? ? ? 2.3.4.3 Anonymous Classes ? 2.3.4.4 Lambda Express ? ? ? 2.3.5 Enum Types ? 2.4 Annotation 2.5Interfaces and Inheritanc 2.6Numbers and String 2.7Generic 2.8Packages ? ? Essential Java Classes 來源:https://www./content-2-393001.html

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多