一些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为后缀名保 ...
随机推荐
- currentTarget,this,target区别
currentTarget : 事件处理程序当前正在处理事件的那个元素 this : 当前的事件发生的元素 target : 事件的目标 currentTarget和this值是始终相等的,但是ta ...
- Java API操作ZK node
创建会话 建立简单连接 /** * 测试创建Zk会话 * Created by liuhuichao on 2017/7/25. */ public class ZooKeeper_Construct ...
- mysql动态扩容调研
MySQL动态扩容方案 目前可用方案 MySQL的复制: 一个Master数据库,多个Salve,然后利用MySQL的异步复制能力实现读写分离,这个方案目前应用比较广泛,这种技术对于以读为主的应用很有 ...
- Java 进阶巩固:什么是注解以及运行时注解的使用
这篇文章 2016年12月13日星期二 就写完了,当时想着等写完另外一篇关于自定义注解的一起发.结果没想到这一等就是半年多 - -. 有时候的确是这样啊,总想着等条件更好了再干,等准备完全了再开始,结 ...
- Vue学习笔记 ——computed VS methods
对于最终的结果,两种方式确实是相同的.然而,不同的是计算属性是基于它们的依赖进行缓存的.计算属性只有在它的相关依赖发生改变时才会重新求值.这就意味着只要 message 还没有发生改变,多次访问 re ...
- Android Dialog 创建上下文菜单
Android Dialog中的listview创建上下文菜单 listView.setOnCreateContextMenuListener(new OnCreateContextMenuListe ...
- [译]TLS中的RC4被攻破了,现在该怎么办?
原文链接:https://community.qualys.com/blogs/securitylabs/2013/03/19/rc4-in-tls-is-broken-now-what 原文发表时间 ...
- Roslyn 的确定性构建
注意到每次编译完之后,你的 dll 或者 exe 是不一样的吗?本来这并没有什么大不了的,但大家都知道数字和鹅厂的安全软件遍布在我们大(tiān)陆(cháo)地区的大量电脑上,它们的查杀策略是——凡 ...
- 携程阿波罗(Apollo)配置中心
携程阿波罗(Apollo) https://www.cnblogs.com/xiaxiaolu/p/10025597.html 一.瞎扯点什么 1.1 阿波罗 阿波罗是希腊神话中的光明之神.文艺之 ...
- [BZOJ3197][SDOI2013]刺客信条assassin
bzoj luogu Description 故事发生在1486 年的意大利,Ezio原本只是一个文艺复兴时期的贵族,后来因为家族成员受到圣殿骑士的杀害,决心成为一名刺客.最终,凭借着他的努力和出众的 ...