一些Java相关的
都是从《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相关的的更多相关文章
- 找工作--Java相关
Hi 各位 首先自我描述一下,80后程序员,现在在做Eclipse插件开发. 求Java相关职位(Java/Swing/Eclipse Plugin/Python etc), 或者Linux下C相关职 ...
- 收集一些java相关的文章
有些文章看了,以后想再看已经忘了在哪里了.故在此一一记录下那些值得看的文章. 1:如何确定Java对象的大小 中文版本 :http://article.yeeyan.org/view/104091/6 ...
- 分享一些JAVA相关资源
前言 以前在学习JAVA时,因为搜索相关资源过于不便,所以在搜集了一些好用的资源之后,将此分享. 文档主要包括面试文档, JAVA的技术文档(如JAVA并发实战.设计模式之类),LINUX的相关文档以 ...
- 【java】Java相关学习参考链接(持续更新)
How to do in java,https://howtodoinjava.com/,Java手册,分版本,并且有每个版本的新特性的详细解析. Java World,https://www.jav ...
- 官网下载java相关资源
官网下载java相关资源 官网地址:http://www.oracle.com 一.下载JDK 1.首先进入Downloads >> Java For Developers,如图 2.点击 ...
- Java相关PDF书籍与教程免费下载
场景 我的CSDN: https://blog.csdn.net/BADAO_LIUMANG_QIZHI 我的博客园: https://www.cnblogs.com/badaoliumangqizh ...
- Awesome Java: Github上关于Java相关的工具
Awesome Java 这是Github上关于Java相关的工具,框架等等资源集合. 原文参考: https://github.com/akullpp/awesome-java. @pdai 最全的 ...
- JAVA相关基础知识
JAVA相关基础知识 1.面向对象的特征有哪些方面 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解全部问题,而只是选择其中的一部分, ...
- JAVA 相关资料
在技术方面无论我们怎么学习,总感觉需要提升自已不知道自己处于什么水平了.但如果有清晰的指示图供参考还是非常不错的,这样我们清楚的知道我们大概处于那个阶段和水平. Java程序员 高级特性 反射.泛型. ...
- Java 相关注意事项小结
程序是一系列有序指令的集合: Java主要用于开发两类程序: 1)桌面应用程序2)Internet应用程序1,Java程序:三步走,编写--编译--运行:2,使用记事本开发:1)以.java为后缀名保 ...
随机推荐
- Python报错IOError: [Errno 22] invalid mode ('r') or filename
IOError: [Errno 22] invalid mode ('r') or filename: 这种错误的出现是在使用built-in函数file()或者open()的时候. 或者是因为文件的 ...
- Python中方法的缺省参数问题分析
引言: 在Python中可以缺省给方法制定缺省值,但是这个缺省值在某些情况下确是和我们预期不太一致的-... 这个诡异的问题,曾经困然了我几天时间,才最终定位出来-.. 测试代码 from datet ...
- SpreadJS 全面支持 Angular2,V10.2 版本即将发布
日前,纯前端表格控件 SpreadJS 发布了最新的CTP版本,在此版本中增加了对 Angular2 的支持以及一些 bug 修复. SpreadJS 纯前端表格控件是基于 HTML5 的 JavaS ...
- @media 照成的问题
多出很大的空白, 原因: left 进行了叠加. 解决办法: 即,不在media里写,将其写在box下
- mailto web弹出outlook发送邮件
1. <pre name="code" class="html"><a href="Mailto:test@163.com?CC=t ...
- Xcode5.1.1支持低版本和image not found和Couldn't register XXXX with the bootstrap server. Error: unknown error code.
一:问题 targets中证书的设置 1.项目支持多设备(Xcode5.1.1支持低版本) 2.真机测试要确保Code Siging 设置没问题 支持的最低版本 二 :问题:image not f ...
- js艺龙
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- HDU3555 Bomb 数位DP第一题
The counter-terrorists found a time bomb in the dust. But this time the terrorists improve on the ti ...
- Hash学习小结
Hash 简要说明 \(OI\)中一般采用进制\(hash\).模数可以用\(unsigned \ long \ long\)自然溢出,也可以使用大质数.值得一提的是,\(unsigned\ long ...
- [BZOJ4061][Cerc2012]Farm and factory
bzoj 鉴于是权限题,放一下题面. Description 向Byteland的国王Bitolomew致敬!国王Bitolomew认为Byteland是一个独一无二的国家.它太小了,它所有的市民(包 ...