都是从《Thinking in Java》英文第四版中摘抄的

_______________________________________________________________________________________________________________________

变量初始化:

The default values are only what Java guarantees when the variable is used as a member of a class. This ensures that member variables of primitive types will always be initialized, reducing a source of bugs. However, this initial value may not be correct or even legal for the program you are writing. It's best to always explicitly initialize your variables.

This guarantee doesn't apply to local variables--those that are not fields of a class.

(也就是方法内部定义的变量,我试了一下,如果只声明不初始化也不使用的话,不会报错,会报警告,如果使用的话,编译时报错)

_______________________________________________________________________________________________________________________

sizeof:

Java has no "sizeof"

In C and C++, the sizeof() operator tells you the number of bytes allocated for data items. The most compelling reason for sizeof() in C and C++ is for portability(可移植性). Different data types might be different sizes on different machines(参看http://www.zhihu.com/question/19580654), so the programmer must discover how big those types are when performing operations that are sensitive to size.For example, one computer might store integers in 32 bits, whereas another might store integers as 16 bits. Programs could store larger values in integers on first machine. As you might imagine, portability is a huge headache for C and C++ programmers.

Java does not need a sizeof() operator for this purpose, because all the data types are the same on all machines. You do not need to think about portability on this level--it is designed into the language.

Java determines the size of each primitive type. These sizes don’t change from one machine architecture to another as they do in most languages. This size invariance is one reason Java programs are more portable than programs in most other languages.

The size of the boolean type is not explicitly specified; it is only defined to be able to take the literal values true or false.

_______________________________________________________________________________________________________________________

if while 的判断条件必须是boolean,不能是int

while(x = y) {
// ....
}

The programmer was clearly tryingto test for equivalence (==) rather than do an assignment. In C and C++ the result of this assignment will always be true if y is nonzero, and you’ll probably get an infinite loop. In Java, the result of this expression is not a boolean, but the compiler expects a boolean and won’t convert from an int, so it will conveniently give you a compile-time error and catch the problem before you ever try to run the program. So the pitfall never happens in Java. (The only time you won’t get a compiletime error is when x and y are boolean, in which case x = y is a legal expression, and in the preceding example, probably an error.)

All conditional statements use the truth or falsehood of a conditional expression to determine the execution path. An example ofa conditional expression is a == b. This uses the conditional operator == to see if the value of ais equivalent to the value of b. The expression returns trueor false. Any of the relational operators you’ve seen in the previous chapter can be used to produce a conditional statement. Notethat Java doesn’t allow you to use a number as a boolean, even though it’s allowed in C and C++ (where truth is nonzero and falsehood is zero). If you want to use a non-booleanin a booleantest, such as if(a), you must first convert it to a boolean value by using a conditional expression, such as if(a != 0).

_______________________________________________________________________________________________________________________

goto:

Although goto is a reserved word in Java, it is not used in the language; Java has no goto.

_______________________________________________________________________________________________________________________

return

You can also see the use of the return keyword, which does two things. First, it means “Leave the method, I’m done.” Second, if the method produces a value, that value is placed right after the return statement.

The returnkeyword has two purposes: It specifies what value a method will return (if it doesn’t have a void return value) and it causes the current method to exit, returning that value.

_______________________________________________________________________________________________________________________

constructor

The constructor is an unusual typeof method because it has no return value. This is distinctly different from a voidreturn value, in which the methodreturns nothing but you still have the option to make it return something else. Constructors return nothing and you don’t have an option (the newexpression does return a reference to the newly created object, but the constructor itself has no return value).

The expression new Bird() creates a new object and calls the default constructor, even though one was not explicitly defined. Without it, you would have no method to call to build the object. However, if you define any constructors (with or without arguments), the compiler will notsynthesize one for you.

_______________________________________________________________________________________________________________________

overloaded 参数类型不同,返回值不同是不可以的

If the methods have the same name, how can Java know which method you mean? There’s a simple rule: Each overloaded method must take a unique list of argument types. If you think about this for a second, it makes sense. How else could a programmer tell the difference between two methods that have the same name, other than by the types of their arguments? Even differences in the ordering of arguments are sufficient to distinguish two methods, although you don’t normally want to take this approach because it produces difficult-tomaintain code.

It is common to wonder, “Why only class names and method argument lists? Why not distinguish between methods based on their return values?” For example, these two methods, which have the same name and arguments, are easily distinguished from each other:
void f() {}
int f() { return 1; }

This might work fine as longas the compiler could unequivocally determine the meaning from the context(我试了,编译器报错了), as in int x = f( ). However, you can also call a method and ignore the return value. This is often referred to as calling a method for its side effect, since you don’t care about the return value, but instead want the other effects of the method call. So if you call the method this way:
f();
how can Java determine which f( ) should be called? And how could someone reading the code see it? Because of this sort of problem, you cannot use return value types to distinguish overloaded methods.

_______________________________________________________________________________________________________________________

this:

1. The thiskeyword—which can be used only inside a non-static method—produces the reference to the object that the method has been called for.

2. The thiskeyword is also useful for passing the current object to another method: (这个用法不熟悉)

 // : initialization/PassingThis.java
class Person {
public void eat(Apple apple) {
Apple peeled = apple.getPeeled();
System.out.println("Yummy");
}
} class Peeler {
static Apple peel(Apple apple) {
// ... remove peel
return apple; // Peeled
}
} class Apple {
Apple getPeeled() {
return Peeler.peel(this);
}
} public class PassingThis {
public static void main(String[] args) {
new Person().eat(new Apple());
}
} /*
* Output: Yummy
*/// :~

Appleneeds to call Peeler.peel( ), which is a foreign utility method that performs an operation that, for some reason, needs to be external to Apple(perhaps the external method can be applied across many different classes, and you don’t want to repeat the code). To pass itself to the foreign method, it must use this.

3. Calling constructors from constructors

 //: initialization/Flower.java
// Calling constructors with "this"
import static net.mindview.util.Print.*; public class Flower {
int petalCount = 0;
String s = "initial value"; Flower(int petals) {
petalCount = petals;
print("Constructor w/ int arg only, petalCount= " + petalCount);
} Flower(String ss) {
print("Constructor w/ String arg only, s = " + ss);
s = ss;
} Flower(String s, int petals) {
this(petals);
// ! this(s); // Can’t call two!
this.s = s; // Another use of "this"
print("String & int args");
} Flower() {
this("hi", 47);
print("default constructor (no args)");
} void printPetalCount() {
// ! this(11); // Not inside non-constructor!
print("petalCount = " + petalCount + " s = " + s);
} public static void main(String[] args) {
Flower x = new Flower();
x.printPetalCount();
}
} /*
* Output: Constructor w/ int arg only, petalCount= 47 String & int args default
* constructor (no args) petalCount = 47 s = hi
*/// :~

The constructor Flower(String s, int petals)shows that, while you can call one constructor using this, you cannot call two. In addition, the constructor call must be the first thing you do, or you’ll get a compiler error message.

In printPetalCount( ) you can see that the compiler won’t let you call a constructor from inside any method other than a constructor.(构造函数中使用this调用构造函数,不能在非构造函数中调用构造函数)

4. This example also shows another way you’ll see thisused. Since the name of the argument s and the name of the member data sare the same, there’s an ambiguity. You can resolve it using this.s, to say that you’re referring to the member data.

_______________________________________________________________________________________________________________________

Static:

With the this keyword in mind, you can more fully understand what it means to make a method static. It means that there is no this for that particular method. You cannot call non-static methods from inside static methods(although the reverse is possible), and you can call a static method for the class itself, without any object. In fact, that’s primarily what a staticmethod is for. It’s as if you’re creating the equivalent of a global method. However, global methods are not permitted in Java, and putting the static method inside a class allows it access to other static methods and to static fields.

Some people argue that static methods are not object-oriented, since they do have the semantics of a global method; with a static method, you don’t send a message to an object, since there’s no this. This is probably a fair argument, and if you find yourself using a lot of static methods, you should probably rethink your strategy. However, statics are pragmatic, and there are times when you genuinely need them, so whether or not they are “proper OOP”
should be left to the theoreticians.

When you say something is static, it means that particular field or method is not tied to any particular object instance of that class. So even if you've never created an object of that class you can call a static method or access a static field. With ordinary, non-static fields and methods, you must create an object and use that object to access that fieldor method, since non-static fields and methods must know the particular object they are working with.Of course, since static methods don't need any objects to be created before they are used, they can't directly access non-static members or methods by simply calling those other members without referring to a named object(since non-static members and methods must be tied to a particular object).

_______________________________________________________________________________________________________________________

inheritance:Initializing the base class

Since there are now two classes involved—the base class and the derived class—instead of just one, it can be a bit confusing to try to imagine the resulting object produced by a derived class. From the outside, it looks like the new class has the same interface as the base class and maybe some additional methods and fields. But inheritance doesn’t just copy the interface of the base class. When you create an object of the derived class, it contains within it a subobject of the base class. This subobject is the same as if you had created an object of the base class by itself. It’s just that from the outside, the subobject of the base class is wrapped within the derived-class object.Of course, it’s essential that the base-class subobject be initialized correctly, and there’s only one way to guarantee this: Perform the initialization in the constructor by calling the base-class constructor, which has all the appropriate knowledge and privileges to perform the base-class initialization. Java automatically inserts calls to the base-class constructor in the derived-class constructor.

下面引自:http://wenku.baidu.com/view/abf0ed8c89eb172dec63b720.html

类的继承机制使得子类可以使用父类的功能(即代码),并且子类也具有父类的类型。下面介绍类在继承关系上的初始化的顺序问题。   
示例1:

 class SuperClass{
SuperClass(){
System.out.println("SuperClass constructor");
}
}
public class SubClass extends SuperClass{
SubClass(){
System.out.println("SubClass constructor");
}
public static void main(String[] args){
SubClass sub = new SubClass();
}
}

输出结果:

SuperClass constructor 

SubClass constructor       

在子类中只实例化了一个子类对象。从输出结果上看,程序并不是一开始就运行自己的构造方法,而是先运行其父类的默认构造方法。注意:程序自动调用其父类的默认构造方法。   
示例2:

 class SuperClass{
SuperClass(String str){
System.out.println("Super with a string.");
}
}
public class SubClass extends SuperClass {
SubClass(String str){
System.out.println("Sub with a string.");
}
public static void main(String[] args){
SubClass sub = new SubClass("sub");
}
}

在JDK 下编译此程序不能成功。正如上例中说的:程序在初始化子类时先要寻找其父类的默认构造方法,结果没找到,那么编译自然不能通过。

解决这个问题有两个办法:  
1.在父类中增加一个默认构造方法。  
2.在子类的构造方法中增加一条语句:super(str); 且必须在第一句。   
这两种方法都能使此程序通过编译,但就本程序来说运行结果却不相同。   
    第1种方法的运行结果是:      Sub with a string.  
    第2 种方法的运行结果是:      Super with a string.      Sub with a string.   
    第 2 种解决方法实际上是指定编译器不要寻找父类的默认构造方法,而是去寻找带一个字符串为参数的构造方法。

一些Java相关的的更多相关文章

  1. 找工作--Java相关

    Hi 各位 首先自我描述一下,80后程序员,现在在做Eclipse插件开发. 求Java相关职位(Java/Swing/Eclipse Plugin/Python etc), 或者Linux下C相关职 ...

  2. 收集一些java相关的文章

    有些文章看了,以后想再看已经忘了在哪里了.故在此一一记录下那些值得看的文章. 1:如何确定Java对象的大小 中文版本 :http://article.yeeyan.org/view/104091/6 ...

  3. 分享一些JAVA相关资源

    前言 以前在学习JAVA时,因为搜索相关资源过于不便,所以在搜集了一些好用的资源之后,将此分享. 文档主要包括面试文档, JAVA的技术文档(如JAVA并发实战.设计模式之类),LINUX的相关文档以 ...

  4. 【java】Java相关学习参考链接(持续更新)

    How to do in java,https://howtodoinjava.com/,Java手册,分版本,并且有每个版本的新特性的详细解析. Java World,https://www.jav ...

  5. 官网下载java相关资源

    官网下载java相关资源 官网地址:http://www.oracle.com 一.下载JDK 1.首先进入Downloads >> Java For Developers,如图 2.点击 ...

  6. Java相关PDF书籍与教程免费下载

    场景 我的CSDN: https://blog.csdn.net/BADAO_LIUMANG_QIZHI 我的博客园: https://www.cnblogs.com/badaoliumangqizh ...

  7. Awesome Java: Github上关于Java相关的工具

    Awesome Java 这是Github上关于Java相关的工具,框架等等资源集合. 原文参考: https://github.com/akullpp/awesome-java. @pdai 最全的 ...

  8. JAVA相关基础知识

    JAVA相关基础知识 1.面向对象的特征有哪些方面 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解全部问题,而只是选择其中的一部分, ...

  9. JAVA 相关资料

    在技术方面无论我们怎么学习,总感觉需要提升自已不知道自己处于什么水平了.但如果有清晰的指示图供参考还是非常不错的,这样我们清楚的知道我们大概处于那个阶段和水平. Java程序员 高级特性 反射.泛型. ...

  10. Java 相关注意事项小结

    程序是一系列有序指令的集合: Java主要用于开发两类程序: 1)桌面应用程序2)Internet应用程序1,Java程序:三步走,编写--编译--运行:2,使用记事本开发:1)以.java为后缀名保 ...

随机推荐

  1. Lodash 浓缩

    Lodash 是个十分有用的工具库,但我们往往只需要其中的一小部分函数.这时,整个 lodash 库就显得十分庞大,我们需要减小 lodash 的体积. cherry-pick 方法 Lodash 官 ...

  2. Shell 命令行 从日志文件中根据将符合内容的日志输出到另一个文件

    Shell 命令行 从日志文件中根据将符合内容的日志输出到另一个文件 前面我写了一篇博文Shell 从日志文件中选择时间段内的日志输出到另一个文件,利用循环实现了我想要实现的内容. 但是用这个脚本的同 ...

  3. 桶排序bucket sort

    桶排序 (Bucket sort)或所谓的箱排序的原理是将数组分到有限数量的桶子里,然后对每个桶子再分别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序),最后将各个桶中的数据有序的 ...

  4. matplotlib 数据可视化

    图的基本结构 通常,使用 numpy 组织数据, 使用 matplotlib API 进行数据图像绘制. 一幅数据图基本上包括如下结构: Data: 数据区,包括数据点.描绘形状 Axis: 坐标轴, ...

  5. [转]redis服务器与客户端保活参数(tcp-keepalive)设置

    最近使用redis的list做跨进程的消息队列,客户端使用的是redis-cplusplus-client.这个client库还是蛮好用的,提供了和redis命令行一致的接口,很方便. 使用过程中发现 ...

  6. Android HOOK工具Cydia Substrate使用详解

    目录(?)[+] Substrate几个重要API介绍 MShookClassLoad MShookMethod 使用方法 短信监控实例   Cydia Substrate是一个代码修改平台.它可以修 ...

  7. HDU3853LOOPS (师傅逃亡系列•三)(基础概率DP)

    Akemi Homura is a Mahou Shoujo (Puella Magi/Magical Girl). Homura wants to help her friend Madoka sa ...

  8. ubuntu下Python的安装和使用

    版权声明 更新:2017-04-13-上午博主:LuckyAlan联系:liuwenvip163@163.com声明:吃水不忘挖井人,转载请注明出处! 1 文章介绍 本文介绍了Python的开发环境. ...

  9. web安全知识

    参考文章 :  https://www.mudoom.com/php%E5%AE%89%E5%85%A8%E7%BC%96%E7%A0%81/ SQL注入 造成sql注入的原因是因为程序没有过滤用户输 ...

  10. BZOJ1725,POJ3254 [Usaco2006 Nov]Corn Fields牧场的安排

    题意 Farmer John新买了一块长方形的牧场,这块牧场被划分成M列N行\((1 \leq M \leq 12, 1 \leq N \leq 12)\),每一格都是一块正方形的土地.FJ打算在牧场 ...