什么是 JAVA 编程思想? 来源: 发表时间:10-01-30 10:49:38 阅读次数:631 什么是 JAVA 编程思想?答案可能很会复杂,但也可以很简单。要了解 JAVA 编程思想,首先 就要了解什么是编程思想,让我们来看看什么是编程思想,一句话来讲就是,用计算机来解 决人们实际问题的思维方式,即编程思想。 我们学习编程语言的最终目的,就是希望用计算机来解决我们的实际问题。那么学习编 程该如何入手,也是很多初学者犯难的一个问题,特别是对与非计算机专业的人来说更是如 此。 面对现实如此多的编程语言 (比如: C,C++,JAVA,C# …) 种类繁多的应用技术 和 (比如: windows 编程, linux 编程, 数据库, 网络编程 …) 确实让人有些眼花缭乱, 。 摸不着头脑。 从下面几点让我们了解下编程的思想。一:过程性的编程思想 计算机只能认识 0 和 1 ,但人却不能只是用 0,1 来写程序。为了程序的写得方便就出 现了 0,1 的第一层抽象标记,汇编语言。汇编里面的那些标记可是直接对应硬件的。硬件生 产厂商都有明确的指令说明书。这些汇编标记是可以被硬件直接识别的。比如 CPU,生产 CPU 的厂家都会有寄存器的标识比如(ax,bx,cx) ,操作指令标识(mov),等等。驱动方面的编程 大多会用到这方面的东西。学习汇编的核心是你需要认识到汇编是一种过程性的编程语言, 并且目前的 CPU 只能执行过程性的程序,任何高级语言都必须转换成过程性的编程语言后再 交给 CPU 执行。在汇编里主要有三个操作:比较,跳转(goto),过程调用(call) 。为什么 说它是过程性的编程思想,值得你去好好的体会一下。不妨写几个算法的程序(在程序里面 用到比较,跳转,过程调用) ,再来看看汇编程序的特点,相信你会有所感悟。值得提一下的 是,如果你对操作系统感兴趣,也可以看看什么是保护模式。 二:结构性的编程思想 随着人们解决的问题越来越复杂,汇编程序当然束缚了计算机软件的发展。因此编程思 想发生了一场革命性的变化, 结构性的编程方法出现了。 在结构性编程思想的编程语言里面, C 语言首当其冲。C 语言里面有几个能表现出结构化思想的地方:分支(if), 循环(while, for),结构体(struct). 只要你会用这三个,那么你就可以写出结构化的程序,但不一定你 就了解什么是结构化的编程方法。 什么叫做结构化?为什么说 goto 会破坏程序的结构化?结 构体有什么作用, 你能说出结构体的哪些好处? 这些都是值得认真体会的地方。 别人给的定 义不见得都全面。还是自己理解比较靠得住。结构化编程里面最具代表性的书籍就要属“数 据结构“
,具体哪本书比较好就不知道了,好像都差不多,只要是用 C 写的就行。C 语言的 “数据结构“里面就是专门来讲怎么用结构性的编程思想来解决实际中的算法问题。看完某 些章节,然后自己找个问题,再用程序去实现它。多写一些程序,会很有帮助。如果第一遍 看完后你看得很模糊,不防先放一放,过一段时间再看看,你可能会有种霍然开朗的感觉。 还有需要说明一下,并不是所有的时候结构化的编程一就定好。某些的时候,结构化的编程 会使程序更繁杂。 (比如结构化编程希望函数只能有一个入口,一个出口。然而有时一个出口 会使程序看起来更繁杂) 三:面向对象的编程思想 现在该说说面向对象编程了。这个也是现在用得最多的编程思想。什么是面向对象,它 和结构性的思想有什么不同?从程序语法上看,面向对象比结构性的程序多了两个特性: 1, 结构体成员的私有化。结构化程序里面,结构体的成员都是公有的。然而在面向对象里面,结构体改称为类,并且成员分为公有和私有两个部分。就因为这一点的不同,就产 生了接口的概念。接口不就是类成员的公有部分么?(想想很好笑,本人刚开始认识面向对 象的时候,以为只有定义成 interface 的才叫做接口) 2, 类的继承。因为出现了继承,才出现了多态。然而就是因为多态,才出现 诸如: 隐藏啊, 虚函数啊 …等等这些概念。 多态的出现, 能够让同一组数据, 在不同的阶段, 用同一种表达方式,执行不同的操作。如果把这个东西领悟到了,那么你会感叹一句”原来 程序是可以这么写的”. 因为以上两点的变化,编程思想也随之发生了巨大转变。它可以让程序更适合人的思维 方法来编写。面向对象的编程语言就很多了,可谓五花八门 :C++ , JAVA , C# …。 都说 C++和 JAVA 有很大的不同,而 JAVA 和 C#却非常相似,你知道为什么吗?最根本区别就在于 垃圾收集器。就是因为 JAVA 里面有垃圾自动收集功能,所以 JAVA 不能和 C 兼容,而且也不 能使用指针。在 C++中的值类型和引用类型是可以自己定义的。如果对象被定义为值类型, 那么当编辑器自动把对象收集走之后,有时自己会一无所知。如果对象被定义为引用类型, 那么又要必须记得把它释放掉,不然又会引起什么内存泄漏的问题。在 JAVA 和 C#里面就不 一样,在这两种语言里面,自定义的类,初始得到的对象只能是引用类型。并且有垃圾收集 器帮你回收垃圾对象。所以就不会出现内存泄漏的问题。 因为 C#比 JAVA 后出来吧,JAVA 所具有的特性, C#基本上都有。 并且还具有一些 JAVA 所不具有的特性 (但 C#目前不能在
第二篇:java编程思想中文308
genesis of the computer revolution was in a machine. The genesis of our programming languages thus tends to look like that machine.
Bruce ?????????Ё????????????????????????????????????8?????????????????????????к??М????г?????????????????????????????????-?▂?????????????????????????Ё????????????????????????????????????????к???????????????????????????????????????????????к????ā????????ā????????????????????????????????????????????????????????????????????????????????????????????????????????П???????????????????????????????????????????????????????????????????к????20027chinapub Bruce Eckel 10007 Bruce Eckel1000The /shhgs/tij.html
2003
?????????????????? Thinking in Java 3rd Edition shhgs 98 1 47 /shhgs/tij.html email:shhgs@sohu.com
???????????????????????????????????????????????????üü?????????????????????????????????????????????????ā???????????????????????????????Мüü???????üü????????c???????????ā?????????????????????????????????????????????????ā???????????????????ā?????????????????????└?????????????????????(interface)(inner clas) C+ava 7abstractinterfaceinterfaceC+(mtipe inheritance) (srronding clas) ?????8: Thinking in Java 3rd Edition (interface) interfaceabstractabstractstaticinalinterfaceinterface interfaceinterfaceinterface(protoco)) (protocolinterfaceclassinterfaceinterface)ackage(interfaceblic(ackage impmets 2 )interfaceinterface 47 /shhgs/tij.html email:shhgs@sohu.com
??????????? Thinking in Java 3rd Edition ????????????????????????????????????????????М????└??????????└└??????????????????????????????????????inBrassinterface interfaceblicinterfaceackageavablicimpmets blicinterface
strumet
interface
blicstrumetblic //: c08:music5:Music5.java // Interfaces.
package c08.music5;
import com.bruceeckel.simpletest.*; import c07.music.Note;
interface Instrument { 3 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition // Compile-time constant:
int I = 5; // static & final
// Cannot have method definitions:
void play(Note n); // Automatically public String what();
void adjust();
}
class Wind implements Instrument {
public void play(Note n) {
System.out.println("Wind.play() " + n); }
public String what() { return "Wind"; }
public void adjust() {}
}
class Percussion implements Instrument {
public void play(Note n) {
System.out.println("Percussion.play() " + n); }
public String what() { return "Percussion"; } public void adjust() {}
}
class Stringed implements Instrument {
public void play(Note n) {
System.out.println("Stringed.play() " + n); }
public String what() { return "Stringed"; } public void adjust() {}
}
class Brass extends Wind {
public void play(Note n) {
System.out.println("Brass.play() " + n); }
public void adjust() {
System.out.println("Brass.adjust()");
}
}
class Woodwind extends Wind {
public void play(Note n) {
System.out.println("Woodwind.play() " + n); }
public String what() { return "Woodwind"; } }
public class Music5 {
private static Test monitor = new Test(); // Doesn't care about type, so new types // added to the system still work right: static void tune(Instrument i) {
// ...
i.play(Note.MIDDLE_C);
}
static void tuneAll(Instrument[] e) {
for(int i = 0; i < e.length; i++)
tune(e[i]);
}
4 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition public static void main(String[] args) {
// Upcasting during addition to the array:
Instrument[] orchestra = {
new Wind(),
new Percussion(),
new Stringed(),
new Brass(),
new Woodwind()
};
tuneAll(orchestra);
monitor.expect(new String[] {
"Wind.play() Middle C",
"Percussion.play() Middle C",
"Stringed.play() Middle C",
"Brass.play() Middle C",
"Woodwind.play() Middle C"
});
}
} ///:~
?ā????????????????????????????????????????????????????ā???????????????strumetstrumetinterface
tu )strumetabstractinterface
strumetabstract
interface????ā?????????āüü????üü????????????????????????ā?????ā???ā???????????????ā?????????????????????Java abstractinterfaceinterfaceC+(ltiple iritace)xinterfaceabc
ava
ava
??????ā
5 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition ???????????ā???????????????????????????????????????????????avaabstract
interfaceinterface)(base elements)impmetsinterfaceabstractinterfaceinterface(
//: c08:Adventure.java
// Multiple interfaces.
interface CanFight {
void fight();
}
interface CanSwim {
void swim();
}
interface CanFly {
void fly();
}
class ActionCharacter {
public void fight() {}
}
class Hero extends ActionCharacter
implements CanFight, CanSwim, CanFly {
public void swim() {}
public void fly() {}
}
public class Adventure {
public static void t(CanFight x) { x.fight(); }
public static void u(CanSwim x) { x.swim(); }
public static void v(CanFly x) { x.fly(); }
public static void w(ActionCharacter x)
{ x.fight(); }
public static void main(String[] args) {
Hero h = new Hero();
t(h); // Treat it as a CanFight
u(h); // Treat it as a CanSwim
6 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition
????????????????????????????????
???????????????????????????????????????М????????????????????????????????
?????????????????????г?????????????????????????ˊ?????????????ā?????????????????????ā???????????????????????????????????????????????????????????????????????????????????
?????????????????????????????????
ro
anigtanim(concrete clas)
(
Actioaracteran)
Actioaracteranigtigt( )
interface
interfaceigt( )
igt( )
ro
(
interface igt( )
)ro
Actioaracter
ro
Adtureinterface
avatye)
ro
(base abstract
interface
abstractinterface
interface
abstract
interface
interfaceabstract
anigt
Actioaracter
id figt( )
//: c08:InterfaceCollision.java
interface I1 { void f(); }
interface I2 { int f(int i); }
v(h); // Treat it as a CanFly
w(h); // Treat it as an ActionCharacter }
} ///:~
7
47
/shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition interface I3 { int f(); }
class C { public int f() { return 1; } }
class C2 implements I1, I2 {
public void f() {}
public int f(int i) { return 1; } // overloaded
}
class C3 extends C implements I2 {
public int f(int i) { return 1; } // overloaded
}
class C4 extends C implements I3 {
// Identical, no problem:
public int f() { return 1; }
}
// Methods differ only by return type:
//! class C5 extends C implements I1 {}
//! interface I4 extends I1, I3 {} ///:~
??▂???????????ā???????
terfceollionttepti to u icomou : it rere voi terfceollioncompatile both d f ) i C caot iplet f ) i I patile return type iterfce I a I are f ) bt wth dret return type ??????????????М????
interface ??????????????г???????????????ac
interfaceinterface
interface
//: c08:HorrorShow.java
// Extending an interface with inheritance.
interface Monster {
void menace();
}
interface DangerousMonster extends Monster {
void destroy();
}
8 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition ??????????????????????ā???????????????????????????ā???????????????????????????? anrosMstersterinterfaceragilaampire (inheriting interfaces) extesinterfaceinterfacextes(base interfaces)interface interface Lethal { void kill(); } class DragonZilla implements DangerousMonster { public void menace() {} public void destroy() {} } interface Vampire extends DangerousMonster, Lethal { void drinkBlood(); } class VeryBadVampire implements Vampire { public void menace() {} public void destroy() {} public void kill() {} public void drinkBlood() {} } public class HorrorShow { static void u(Monster b) { b.menace(); } static void v(DangerousMonster d) { d.menace(); d.destroy(); } static void w(Lethal l) { l.kill(); } public static void main(String[] args) { DangerousMonster barney = new DragonZilla(); u(barney); v(barney); Vampire vlad = new VeryBadVampire(); u(vlad); v(vlad); w(vlad); } } ///:~ interfaceinterfaceC+m 9 staticinal C 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition //: c08:Months.java
// Using interfaces to create groups of constants.
package c08;
public interface Months {
int
JANUARY = 1, FEBRUARY = 2, MARCH = 3,
APRIL = 4, MAY = 5, JUNE = 6, JULY = 7,
AUGUST = 8, SEPTEMBER = 9, OCTOBER = 10,
NOVEMBER = 11, DECEMBER = 12;
} ///:~
????????????????????????????????????????????????????????????????????????????????????????????????????ā?????????????????????ava)(static final interface ic c0thsths.ANUARint()ackage imprt c0ackageC+m(
)
//: c08:Month.java
// A more robust enumeration system.
package c08;
import com.bruceeckel.simpletest.*;
public final class Month {
private static Test monitor = new Test();
private String name;
private Month(String nm) { name = nm; }
public String toString() { return name; }
public static final Month
JAN = new Month("January"),
FEB = new Month("February"),
MAR = new Month("March"),
APR = new Month("April"),
MAY = new Month("May"),
JUN = new Month("June"),
JUL = new Month("July"),
AUG = new Month("August"),
SEP = new Month("September"),
OCT = new Month("October"),
NOV = new Month("November"),
DEC = new Month("December");
public static final Month[] month = {
JAN, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC
};
10 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition ???????????????????????????????????????????????????????????М?????????????????????????????????????П???М?????????????????????????????????????????????????????????М???ā???????-?????????? thrivateEBinalstaticANmber( )th ARththmththavaintmain ) intmain )als( )th ava.tilalarnth ache Jakarta Cons public static final Month number(int ord) { return month[ord - 1]; } public static void main(String[] args) { Month m = Month.JAN; System.out.println(m); m = Month.number(12); System.out.println(m); System.out.println(m == Month.DEC); System.out.println(m.equals(Month.DEC)); System.out.println(Month.month[3]); monitor.expect(new String[] { "January", "December", "true", "true", "April" }); } } ///:~ inal moth
?????Ё?????
11 /commonsrgapachcommos.anm ang 47 /shhgs/tij.html email:shhgs@sohu.com
?finalstaticinal
//: c08:RandVals.java
// Initializing interface fields with // non-constant initializers. import java.util.*;
public interface RandVals { Random rand = new Random(); int randomInt = rand.nextInt(10); long randomLong = rand.nextLong() * 10; float randomFloat = rand.nextLong() * 10; double randomDouble = rand.nextDouble() * 10; } ///:~ Thinking in Java 3rd Edition ??????????????г????????????static
//: c08:TestRandVals.java import com.bruceeckel.simpletest.*;
public class TestRandVals {
private static Test monitor = new Test(); public static void main(String[] args) { System.out.println(RandVals.randomInt); System.out.println(RandVals.randomLong); System.out.println(RandVals.randomFloat); System.out.println(RandVals.randomDouble); monitor.expect(new String[] { "%% -?\\d+",
"%% -?\\d+",
"%% -?\\d\\.\\d+E?-?\\d+", "%% -?\\d\\.\\d+E?-?\\d+" });
}
} ///:~
????
????????????????????? ??????г????????????? //: c08:nesting:NestingInterfaces.java package c08.nesting; 12 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition class A {
interface B {
void f();
}
public class BImp implements B {
public void f() {}
}
private class BImp2 implements B {
public void f() {}
}
public interface C {
void f();
}
class CImp implements C {
public void f() {}
}
private class CImp2 implements C {
public void f() {}
}
private interface D {
void f();
}
private class DImp implements D {
public void f() {}
}
public class DImp2 implements D {
public void f() {}
}
public D getD() { return new DImp2(); } private D dRef;
public void receiveD(D d) {
dRef = d;
dRef.f();
}
}
interface E {
interface G {
void f();
}
// Redundant "public":
public interface H {
void f();
}
void g();
// Cannot be private within an interface: //! private interface I {}
}
public class NestingInterfaces {
public class BImp implements A.B {
public void f() {}
}
class CImp implements A.C {
public void f() {}
}
// Cannot implement a private interface except // within that interface's defining class: //! class DImp implements A.D {
//! public void f() {}
13 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition //! }
class EImp implements E {
public void g() {}
}
class EGImp implements E.G {
public void f() {}
}
class EImp2 implements E {
public void g() {}
class EG implements E.G {
public void f() {}
}
}
public static void main(String[] args) {
A a = new A();
// Can't access A.D:
//! A.D ad = a.getD();
// Doesn't return anything but A.D:
//! A.DImp2 di2 = a.getD();
// Cannot access a member of the interface:
//! a.getD().f();
// Only another A can do anything with getD():
A a2 = new A();
a2.receiveD(a.getD());
}
} ///:~
??????????????????????└????└???????└????ā?
??????????????ā?г???ā??М???????????????????????????????????????ā???????????????????????ā??????????????????????????????????????????????????üü??????blicblicackagerivateA.ackageblic(nested clases) ackagerivate(nested clases)nested interfacesrivate rivatempA.mpA.mprivate)blicrivate( tD )rivate
rivate
main )
Areferencereceiv )
blic 14 47 /shhgs/tij.html email:shhgs@sohu.com
ü?????????????????????????????????????????????????????????
????????????ā?????????????????????ā???????????????????????????????????????└??????????????
????????????????????????ā??????????üü??????Eblicblicrivate stinterfacesrivate Thinking in Java 3rd Edition class)(nner
(srronding clas)
//: c08:Parcel1.java
// Creating inner classes.
public class Parcel1 {
class Contents {
private int i = 11;
public int value() { return i; } }
class Destination {
private String label; Destination(String whereTo) { label = whereTo;
}
String readLabel() { return label; } }
// Using inner classes looks just like // using any other class, within Parcel1: public void ship(String dest) { Contents c = new Contents(); Destination d = new Destination(dest); System.out.println(d.readLabel()); }
public static void main(String[] args) { Parcel1 p = new Parcel1(); p.ship("Tanzania");
}
15 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition } ///:~
????????????????????????????
????????????????????ship )
arce
reference
//: c08:Parcel2.java
// Returning a reference to an inner class.
public class Parcel2 {
class Contents {
private int i = 11;
public int value() { return i; }
}
class Destination {
private String label;
Destination(String whereTo) {
label = whereTo;
}
String readLabel() { return label; }
}
public Destination to(String s) {
return new Destination(s);
}
public Contents cont() {
return new Contents();
}
public void ship(String dest) {
Contents c = cont();
Destination d = to(dest);
System.out.println(d.readLabel());
}
public static void main(String[] args) {
Parcel2 p = new Parcel2();
p.ship("Tanzania");
Parcel2 q = new Parcel2();
// Defining references to inner classes: Parcel2.Contents c = q.cont();
Parcel2.Destination d = q.to("Borneo"); }
} ///:~
???????ā??????????????????????????????(oter clas)
16 staticterCassName.InnerCassName main ) /shhgs/tij.html email:shhgs@sohu.com 47
?????М?üü??└????????????????????????????????????????????????üü????????ā??????????????????????????????ā?(ackageava)ackage interface()interface
interfacereference
//: c08:Destination.java public interface Destination { String readLabel();
} ///:~ Thinking in Java 3rd Edition
//: c08:Contents.java
public interface Contents { int value();
} ///:~
?????????????????????????? interfacetetsstinatioblic) (interfacereference
//: c08:TestParcel.java
// Returning a reference to an inner class.
class Parcel3 {
private class PContents implements Contents { private int i = 11; public int value() { return i; } }
protected class PDestination implements Destination {
private String label;
private PDestination(String whereTo) { label = whereTo; }
public String readLabel() { return label; } }
public Destination dest(String s) { return new PDestination(s); }
public Contents cont() { return new PContents(); 17 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition ???????????????????????????????????????????└???????????????????└??└???????????????????????????????????????ā?????????????????ā??????????????????г????????????????└????
???????????????????????ā????????????????????????????????М?ˊ?
?????????????????????????????М??? tetsmain ) arcearcearce)arcetetrivatestinatiorotecteackage(rotectestinatio(rotecteclass TstParcerivaterivate)coing dependencies)(tye-interfaceblic interface ava()blicackagrivate rotecte } } public class TestParcel { public static void main(String[] args) { Parcel3 p = new Parcel3(); Contents c = p.cont(); Destination d = p.dest("Tanzania"); // Illegal -- can't access private class: //! Parcel3.PContents pc = p.new PContents(); } } ///:~ 1.
.
18 47 /shhgs/tij.html email:shhgs@sohu.com
???????????????????????????????ā????????????????????ā?????????????
1. 2. 3. 4. 5. .
(
)
rapin
//: c08:Wrapping.java public class Wrapping { private int i;
public Wrapping(int x) { i = x; } public int value() { return i; } } ///:~
Thinking in Java 3rd Edition
????????????????????????????????????????ā?
rapin
(
(ocalnner class)
)
//: c08:Parcel4.java
// Nesting a class within a method.
public class Parcel4 {
public Destination dest(String s) {
class PDestination implements Destination { private String label;
private PDestination(String whereTo) { label = whereTo; }
public String readLabel() { return label; } }
return new PDestination(s); }
public static void main(String[] args) { Parcel4 p = new Parcel4();
Destination d = p.dest("Tanzania"); }
} ///:~
?????????????????????????????М???
stinatioarce(
stinatio
st( )
)
19
47
/shhgs/tij.html email:shhgs@sohu.com
üü????????????????????????????st( )st( )stinatio
st( )
stinatiostinatiostinstinreferenceatio st( )atio
//: c08:Parcel5.java // Nesting a class within a scope.
public class Parcel5 {
private void internalTracking(boolean b) { if(b) {
class TrackingSlip { private String id; TrackingSlip(String s) { id = s; }
String getSlip() { return id; } }
TrackingSlip ts = new TrackingSlip("slip"); String s = ts.getSlip(); }
// Can't use it here! Out of scope: //! TrackingSlip ts = new TrackingSlip("x"); }
public void track() { internalTracking(true); } public static void main(String[] args) { Parcel5 p = new Parcel5(); p.track();
}
} ///:~ Thinking in Java 3rd Edition ?????????????üü?????????└???????????? rackinipif
//: c08:Parcel6.java
// A method that returns an anonymous inner class.
public class Parcel6 { public Contents cont() { return new Contents() { private int i = 11; public int value() { return i; } }; // Semicolon required in this case }
20 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition ????????ā??????????????????????????
cot( )
tets
return new Contents() public static void main(String[] args) { Parcel6 p = new Parcel6(); Contents c = p.cont(); } } ///:~
?????????????????ā?
return new Contents() {
private int i = 11;
public int value() { return i; }
};
????????????????ā??????????????tets
tetsreference
class MyContents implements Contents {
private int i = 11;
public int value() { return i; }
}
return new MyContents();
??????????????????????ā?????tets
//: c08:Parcel7.java
// An anonymous inner class that calls
// the base-class constructor.
public class Parcel7 {
public Wrapping wrap(int x) {
// Base constructor call:
return new Wrapping(x) { // Pass constructor
argument.
public int value() {
21 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition ?????????????????????
???????????????????????????????????????????????? Wrapinx) x(C+)
//: c08:Parcel8.java
// An anonymous inner class that performs
// initialization. A briefer version of Parcel4.java.
public class Parcel8 {
// Argument must be final to use inside
// anonymous inner class:
public Destination dest(final String dest) {
return new Destination() {
private String label = dest;
public String readLabel() { return label; }
};
}
public static void main(String[] args) {
Parcel8 p = new Parcel8();
Destination d = p.dest("Tanzania");
}
} ///:~ return super.value() * 47; } }; // Semicolon required } public static void main(String[] args) { Parcel7 p = new Parcel7(); Wrapping w = p.wrap(10); } } ///:~
??????????????????????????????????????М??????????????ā???????????????????????ā??????referenceinalst( ) (
(nstance nitialation)
)
22 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition //: c08:AnonymousConstructor.java
// Creating a constructor for an anonymous inner
class.
import com.bruceeckel.simpletest.*;
abstract class Base {
public Base(int i) {
System.out.println("Base constructor, i = " + i); }
public abstract void f();
}
public class AnonymousConstructor {
private static Test monitor = new Test();
public static Base getBase(int i) {
return new Base(i) {
{
System.out.println("Inside instance
initializer");
}
public void f() {
System.out.println("In anonymous f()");
}
};
}
public static void main(String[] args) {
Base base = getBase(47);
base.f();
monitor.expect(new String[] {
"Base constructor, i = 47",
"Inside instance initializer",
"In anonymous f()"
});
}
} ///:~
??????????????????
????????ā???????iinali
arcelst( )
inal
//: c08:Parcel9.java
// Using "instance initialization" to perform
// construction on an anonymous inner class.
import com.bruceeckel.simpletest.*;
public class Parcel9 {
private static Test monitor = new Test();
public Destination
dest(final String dest, final float price) {
return new Destination() {
private int cost;
// Instance initialization for each object:
{
cost = Math.round(price);
23 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition if(cost > 100)
System.out.println("Over budget!");
}
private String label = dest;
public String readLabel() { return label; }
};
}
public static void main(String[] args) {
Parcel9 p = new Parcel9();
Destination d = p.dest("Tanzania", 101.395F);
monitor.expect(new String[] {
"Over budget!"
});
}
} ///:~
???ā???????????ā??????????????????????└????????
????????????????г????????????????????М???????????????ā?????????üü????????????????(if) (encling oect)
//: c08:Sequence.java
// Holds a sequence of Objects.
import com.bruceeckel.simpletest.*;
interface Selector {
boolean end();
Object current();
void next();
}
public class Sequence {
private static Test monitor = new Test();
private Object[] objects;
private int next = 0;
public Sequence(int size) { objects = new
Object[size]; }
public void add(Object x) {
if(next < objects.length)
objects[next++] = x;
}
private class SSelector implements Selector {
private int i = 0;
24 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition
cead )
)?????????????????????????????????????????????
???????????????????????????????ā???????????????????????????????????????
??????????????üü???üü??????????????????????????????????????bjctbjct(ctorce )bjctcurret( )cebjctxt( )ctorinterfaceinterfaceinterface(generic coe) ctormain )ctorcetSctor( )ce rivatetrinctorctor
)curret( )
bjctctorxt( )rivate
25 public boolean end() { return i == objects.length; } public Object current() { return objects[i]; } public void next() { if(i < objects.length) i++; } } public Selector getSelector() { return new SSelector(); } public static void main(String[] args) { Sequence sequence = new Sequence(10); for(int i = 0; i < 10; i++) sequence.add(Integer.toString(i)); Selector selector = sequence.getSelector(); while(!selector.end()) { System.out.println(selector.current()); selector.next(); } monitor.expect(new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }); } } ///:~ 47 /shhgs/tij.html email:shhgs@sohu.com
static????????ā???????????????????????????????????????????????????????????????????????ā??М??????ā??????????????????????????г?????????ā????????????????????????????????????????????????????????????????????????????reference)reference(referencereference Thinking in Java 3rd Edition staticstatic(nestedclass)reference1. . static static static
//: c08:Parcel10.java
// Nested classes (static inner classes).
public class Parcel10 {
private static class ParcelContents implements Contents {
private int i = 11;
public int value() { return i; }
}
protected static class ParcelDestination
implements Destination {
private String label;
private ParcelDestination(String whereTo) { label = whereTo;
}
public String readLabel() { return label; } // Nested classes can contain other static
elements:
public static void f() {}
static int x = 10;
static class AnotherLevel {
public static void f() {}
static int x = 10;
}
}
public static Destination dest(String s) {
return new ParcelDestination(s);
47 26 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition }
public static Contents cont() {
return new ParcelContents();
}
public static void main(String[] args) {
Contents c = cont();
Destination d = dest("Tanzania");
}
} ///:~
?????????????????????????
????????????????????????????????????????????????üü????????main )arcestaticstinatioreference tetsreferencereference
interface(static)static this interfacestaticinterface
//: c08:IInterface.java
// Nested classes inside interfaces.
public interface IInterface {
static class Inner {
int i, j, k;
public Inner() {}
void f() {}
}
} ///:~ this
??????????????????????????????????М???
main )
//: c08:TestBed.java
// Putting test code in a nested class.
public class TestBed {
public TestBed() {}
public void f() { System.out.println("f()"); }
public static class Tester {
public static void main(String[] args) {
TestBed t = new TestBed();
t.f();
}
}
27 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition } ///:~
????????????М??????????????????????????????????????????????????????????М??????referencethiscector(cereferencecethis
)
reference
//: c08:Parcel11.java
// Creating instances of inner classes.
public class Parcel11 {
class Contents {
private int i = 11;
public int value() { return i; }
}
class Destination {
private String label;
Destination(String whereTo) { label = whereTo; }
String readLabel() { return label; }
}
public static void main(String[] args) {
Parcel11 p = new Parcel11();
// Must use instance of outer class
// to create an instances of the inner class:
Parcel11.Contents c = p.new Contents();
Parcel11.Destination d = p.new
Destination("Tanzania");
}
} ///:~ ?????????????????????????????stBe$Tster class ava TstBe$Tster) (stBe$Tster.class
??????????????????????????arce
Parcel11.Contents c = p.new Contents();
28 47 /shhgs/tij.html email:shhgs@sohu.com
????????????????????????????????????????üü?????????(static)reference Thinking in Java 3rd Edition
//: c08:MultiNestingAccess.java
// Nested classes can access all members of all // levels of the classes they are nested within.
class MNA {
private void f() {}
class A {
private void g() {}
public class B {
void h() {
g();
f();
}
}
}
}
public class MultiNestingAccess { public static void main(String[] args) { MNA mna = new MNA(); MNA.A mnaa = mna.new A(); MNA.A.B mnaab = mnaa.new B(); mnaab.h();
}
} ///:~
??????????????????????????ā???????????└???????????????????????▂???????????ā???????????????????A.A.Brivate) ) )( reference
reference
29 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition //: c08:InheritInner.java
// Inheriting an inner class.
class WithInner {
class Inner {}
}
public class InheritInner extends WithInner.Inner {
//! InheritInner() {} // Won't compile
InheritInner(WithInner wi) {
wi.super();
}
public static void main(String[] args) {
WithInner wi = new WithInner();
InheritInner ii = new InheritInner(wi);
}
} ///:~
?????????????????????????????????????ritIr
reference
enclosingClassReference.super();
????????????????????????????????????ā??????????????????????reference
//: c08:BigEgg.java
// An inner class cannot be overriden like a method.
import com.bruceeckel.simpletest.*;
class Egg {
private Yolk y;
protected class Yolk {
public Yolk()
{ System.out.println("Egg.Yolk()"); }
}
public Egg() {
System.out.println("New Egg()");
y = new Yolk();
}
}
public class BigEgg extends Egg {
30 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition private static Test monitor = new Test();
public class Yolk {
public Yolk()
{ System.out.println("BigEgg.Yolk()"); }
}
public static void main(String[] args) {
new BigEgg();
monitor.expect(new String[] {
"New Egg()",
"Egg.Yolk()"
});
}
} ///:~
??????????????????????????????????????????????????????????????????????????BigEg
//: c08:BigEgg2.java
// Proper inheritance of an inner class.
import com.bruceeckel.simpletest.*;
class Egg2 {
protected class Yolk {
public Yolk()
{ System.out.println("Egg2.Yolk()"); }
public void f()
{ System.out.println("Egg2.Yolk.f()");}
}
private Yolk y = new Yolk();
public Egg2() { System.out.println("New Egg2()"); }
public void insertYolk(Yolk yy) { y = yy; }
public void g() { y.f(); }
}
public class BigEgg2 extends Egg2 {
private static Test monitor = new Test();
public class Yolk extends Egg2.Yolk {
public Yolk()
{ System.out.println("BigEgg2.Yolk()"); }
public void f() {
System.out.println("BigEgg2.Yolk.f()");
}
}
public BigEgg2() { insertYolk(new Yolk()); }
public static void main(String[] args) {
Egg2 e2 = new BigEgg2();
e2.g();
monitor.expect(new String[] {
"Egg2.Yolk()",
"New Egg2()",
31 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition "Egg2.Yolk()",
"BigEgg2.Yolk()",
"BigEgg2.Yolk.f()"
});
}
} ///:~
?????????????????????????????????????
?????????????????????????????????????????BigEginsertY )Eg reference )BigEgEg ) ) xtes EgBigEg ) ) )(L i c) final
//: c08:LocalInnerClass.java
// Holds a sequence of Objects.
import com.bruceeckel.simpletest.*;
interface Counter {
int next();
}
public class LocalInnerClass {
private static Test monitor = new Test();
private int count = 0;
Counter getCounter(final String name) {
// A local inner class:
class LocalCounter implements Counter {
public LocalCounter() {
// Local inner class can have a constructor
System.out.println("LocalCounter()");
}
public int next() {
System.out.print(name); // Access local
final
return count++;
}
}
return new LocalCounter();
}
// The same thing with an anonymous inner class:
Counter getCounter2(final String name) {
return new Counter() {
// Anonymous inner class cannot have a named
// constructor, only an instance initializer:
{
32 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition ????????????????????????????????????????ˊ?????????????????
???????????????????
?ā???????????????ā?????????????????????????ā??? ter/ System.out.println("Counter()"); } public int next() { System.out.print(name); // Access local final return count++; } }; } public static void main(String[] args) { LocalInnerClass lic = new LocalInnerClass(); Counter c1 = lic.getCounter("Local inner "), c2 = lic.getCounter2("Anonymous inner "); for(int i = 0; i < 5; i++) System.out.println(c1.next()); for(int i = 0; i < 5; i++) System.out.println(c2.next()); monitor.expect(new String[] { "LocalCounter()", "Counter()", "Local inner 0", "Local inner 1", "Local inner 2", "Local inner 3", "Local inner 4", "Anonymous inner 5", "Anonymous inner 6", "Anonymous inner 7", "Anonymous inner 8", "Anonymous inner 9" }); } } ///:~ (I c i) class
clas)(asseta-ass
class/
33 47 /shhgs/tij.html email:shhgs@sohu.com
calrCass.ava$class
Counter.class
LocalInnerClass$2.class
LocalInnerClass$1LocalCounter.class
LocalInnerClass.class Thinking in Java 3rd Edition
???????????????????????М????????????
?????????????????????????????????????????????М?????????????????????????????ā????М????
?????????????????????????????????????????????????????????????????ā?М???????????????????????????????????????????????????????????????????????????ā?
?????????????????????????????????????????????????āг??????????????$ ava(ava) n interface referenceinterfaceinterfaceinterfaceinterfaceinterface abstractimementation inheritance)
interface (mtipe
34 47 /shhgs/tij.html email:shhgs@sohu.com
????????????????????????? //: c08:MultiInterfaces.java
// Two ways that a class can implement multiple interfaces.
interface A {}
interface B {}
class X implements A, B {}
class Y implements A {
B makeB() {
// Anonymous inner class: return new B() {};
}
}
public class MultiInterfaces { static void takesA(A a) {} static void takesB(B b) {} public static void main(String[] args) { X x = new X();
Y y = new Y();
takesA(x);
takesA(y);
takesB(x);
takesB(y.makeB());
}
} ///:~ Thinking in Java 3rd Edition ???????????????????????????????????????????????????????????????????????М????
interfaceabstract
//: c08:MultiImplementation.java // With concrete or abstract classes, inner // classes are the only way to produce the effect // of "multiple implementation inheritance." package c08;
class D {}
abstract class E {}
class Z extends D {
E makeE() { return new E() {}; } }
35 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition
closure
??ā???????М????????????????????????????????????????????????????????????????М?????????????????ā???????????????ā????????М?????????????????????????????????????????????????????????????????ā???????????????????????????????????????????????╓???????????????????????????????????????????????üü?г??
inheritance)1. 2.
(mtipe imementation
interface
3. 4.
ceava
cector
ctor
tRctor( )ctor
ce
public class MultiImplementation { static void takesD(D d) {} static void takesE(E e) {}
public static void main(String[] args) { Z z = new Z(); takesD(z);
takesE(z.makeE()); }
} ///:~
Closure(Closures & Callbs)
clre
(
referencerivate
)
ava
(callbck)
ava
clre
36
47
/shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition //: c08:Callbacks.java
// Using inner classes for callbacks
import com.bruceeckel.simpletest.*;
interface Incrementable {
void increment();
}
// Very simple to just implement the interface: class Callee1 implements Incrementable {
private int i = 0;
public void increment() {
i++;
System.out.println(i);
}
}
class MyIncrement {
void increment() {
System.out.println("Other operation");
}
static void f(MyIncrement mi) { mi.increment(); } }
// If your class must implement increment() in // some other way, you must use an inner class: class Callee2 extends MyIncrement {
private int i = 0;
private void incr() {
i++;
System.out.println(i);
}
private class Closure implements Incrementable { public void increment() { incr(); }
}
Incrementable getCallbackReference() {
return new Closure();
}
}
class Caller {
private Incrementable callbackReference;
Caller(Incrementable cbh) { callbackReference = cbh; }
void go() { callbackReference.increment(); } }
public class Callbacks {
private static Test monitor = new Test();
public static void main(String[] args) {
Callee1 c1 = new Callee1();
Callee2 c2 = new Callee2();
MyIncrement.f(c2);
Caller caller1 = new Caller(c1);
Caller caller2 = new
Caller(c2.getCallbackReference());
caller1.go();
caller1.go();
caller2.go();
caller2.go();
37 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition
monitor.expect(new String[] { "Other operation", "1", "2", "1", "2" }); }
} ///:~
??ā?????????ā??????????????raeworks)
raework)
(conrol
(licaon fraework)
??
?????????ā?????āП??????????????????????????????????????????????????????????????????????????????????????????????????üü???????????????????????????????????ā?????????ā???????????????????????????
alcremet
incremet( )
alcremetablalcremet
cremetablcremetincremet( )
tCalbackrece ) Calrivateinterface Icremetabl interface
sure
cremetabl(
alr2
cremetablincremet( )alr
reference
cremetabl
reference(
referencereference
)
al
)
(Ier classes & conrol
38
47
/shhgs/tij.html email:shhgs@sohu.com
?????????????????????ā???????????ā???М??????????????????????????????????????▂?????????????????????ā?????????ā????????????????ā?????????ā???????????????????????????????????) (ruceEckel.com(Temate Meth) i Perns( (G)(even-drien system)avaing abstractinterface
//: c08:controller:Event.java // The common methods for any control event. package c08.controller;
public abstract class Event { private long eventTime; protected final long delayTime; public Event(long delayTime) { this.delayTime = delayTime; start();
}
public void start() { // Allows restarting eventTime = System.currentTimeMillis() + delayTime;
}
public boolean ready() {
return System.currentTimeMillis() >= eventTime; }
public abstract void action(); } ///:~ Thinking in Java 3rd Edition ????????????????????????????????П?????????????????Evt)(start( )start( )start( )Evtactio ) 39 start( ) 47 /shhgs/tij.html email:shhgs@sohu.com
read )
read )???????????
???????????????????????????????????????????actio )
Evt
Arrayist
Arrayistad )
Arrayistsiz )Arrayist
t( )Arrayistremo )Arrayist
//: c08:controller:Controller.java
// With Event, the generic framework for control
systems.
package c08.controller;
import java.util.*;
public class Controller {
// An object from java.util to hold Event objects: private List eventList = new ArrayList();
public void addEvent(Event c) { eventList.add(c); } public void run() {
while(eventList.size() > 0) {
for(int i = 0; i < eventList.size(); i++) {
Event e = (Event)eventList.get(i);
if(e.ready()) {
System.out.println(e);
e.action();
eventList.remove(i);
}
}
}
}
} ///:~ Thinking in Java 3rd Edition Evtbjct??????????????????????????????????????????üü??????ā???????????ā???????????????????????????????????ā?????????????? ru ) tListread )actio )read )Evttotrin )Evt Evt(vector of change)EvtEvt
1.
actio )
47 40 /shhgs/tij.html email:shhgs@sohu.com
????????????????????????????????????????????????????????????????????????????????????2. Thinking in Java 3rd Edition Evt
Evtactio ) tror resetros//: c08:GreenhouseControls.java // This produces a specific application of the // control system, all in a single class. Inner // classes allow you to encapsulate different // functionality for each type of event. import com.bruceeckel.simpletest.*; import c08.controller.*;
public class GreenhouseControls extends Controller { private static Test monitor = new Test(); private boolean light = false; public class LightOn extends Event { public LightOn(long delayTime) { super(delayTime); } public void action() {
// Put hardware control code here to // physically turn on the light. light = true; }
public String toString() { return "Light is on"; }
}
public class LightOff extends Event { public LightOff(long delayTime) { super(delayTime); } public void action() {
// Put hardware control code here to // physically turn off the light. light = false; }
public String toString() { return "Light is off"; }
}
private boolean water = false; public class WaterOn extends Event { public WaterOn(long delayTime) { super(delayTime); } public void action() { // Put hardware control code here. water = true; }
public String toString() { return "Greenhouse water is on"; 47 41 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition }
}
public class WaterOff extends Event {
public WaterOff(long delayTime)
{ super(delayTime); }
public void action() {
// Put hardware control code here.
water = false;
}
public String toString() {
return "Greenhouse water is off";
}
}
private String thermostat = "Day";
public class ThermostatNight extends Event { public ThermostatNight(long delayTime) {
super(delayTime);
}
public void action() {
// Put hardware control code here.
thermostat = "Night";
}
public String toString() {
return "Thermostat on night setting";
}
}
public class ThermostatDay extends Event {
public ThermostatDay(long delayTime) {
super(delayTime);
}
public void action() {
// Put hardware control code here.
thermostat = "Day";
}
public String toString() {
return "Thermostat on day setting";
}
}
// An example of an action() that inserts a
// new one of itself into the event list:
public class Bell extends Event {
public Bell(long delayTime) { super(delayTime); } public void action() {
addEvent(new Bell(delayTime));
}
public String toString() { return "Bing!"; } }
public class Restart extends Event {
private Event[] eventList;
public Restart(long delayTime, Event[] eventList) {
super(delayTime);
this.eventList = eventList;
for(int i = 0; i < eventList.length; i++) addEvent(eventList[i]);
}
public void action() {
for(int i = 0; i < eventList.length; i++) { eventList[i].start(); // Rerun each event addEvent(eventList[i]);
42 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition ??????????└????????????????????????????
???????????????????????ā??????????????????????????????????????????ā???? igtaterthrmostatresetrosactio ) EvtBeBestartBeBestartEvtresetros startEvt(controer)start( )Evtstart.actio )start
resetrosEvt(om)
//: c08:GreenhouseController.java
// Configure and execute the greenhouse system.
// {Args: 5000}
import c08.controller.*;
public class GreenhouseController {
public static void main(String[] args) {
GreenhouseControls gc = new GreenhouseControls(); // Instead of hard-wiring, you could parse
// configuration information from a text file
here:
gc.addEvent(gc.new Bell(900));
Event[] eventList = {
gc.new ThermostatNight(0),
} start(); // Rerun this Event addEvent(this); } public String toString() { return "Restarting system"; } } public class Terminate extends Event { public Terminate(long delayTime) { super(delayTime); } public void action() { System.exit(0); } public String toString() { return "Terminating"; } } } ///:~ 43 47 /shhgs/tij.html email:shhgs@sohu.com
Thinking in Java 3rd Edition gc.new LightOn(200),
gc.new LightOff(400),
gc.new WaterOn(600),
gc.new WaterOff(800),
gc.new ThermostatDay(1400)
};
gc.addEvent(gc.new Restart(2000, eventList));
if(args.length == 1)
gc.addEvent(
gc.new Terminate(Integer.parseInt(args[0])));
gc.run();
}
} ///:~
????????????????????????????????????М????????????
???????????????????????????????????????????()()
????????????????????????????????????????
????????????╓??????????????????????????????????????╓????????
????????????????? C+C+(M)C+ ava ?????
ruceEckel.com i J Aoted Soluton Guie
interfacee staticinal 44 47 /shhgs/tij.html email:shhgs@sohu.com
ackageinterface
ackage interfaceblic c0anichavaastF(
)anichastF 5. interfaceinterfaceinterface
interface
interfacemain )
6. 5abtract 7. sic5avaayabl interfaceay )
strumetayablayabltu )ayablstrumet 76tinterface Adtureavaanimb
thava thava ackageinterface
interfaceroctecteackagerotecte
interface interface
interfacereference
5. rrorSavaanrosMsterampire 6. blic interfacerivate
rivatereferenceinterface
7. ()
()
reference
rivaterivate
???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????ā????????????????????????????? Thinking in Java 3rd Edition 45 47 /shhgs/tij.html email:shhgs@sohu.com
5. 6.
inError.ava ceavatRctor( )ctor interfacector
7. interface U
UreferenceA
UBBUreference
reference () U
main )ABAUreferenceBBABUreference resetros.ava(fan)Evtresetros.ava
Evt
resetros.avaresetros
Evt
resetror.avaEvt rivate
???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????ā??????????????????????????????????????????????????????????????????????????????????????????????????????????????????
main )
interface
interfaceclass)
(
a Bch
ecte
Thinking in Java 3rd Edition
??????????????????????????āП????????????????г????
Rich Hffarthemail
(Aisn-Wesey 2)
artin Danner
C+
(ested classes)
C+
46
47
/shhgs/tij.html email:shhgs@sohu.com
????????????????????????????????????????????????????????????Thinking in Java 3rd Edition rivateC+ C+avaartin Danner$ nix selnclassnix
sie & Out
ava
47 47 /shhgs/tij.html email:shhgs@sohu.com