java中构造函数的调用顺序
当一个复杂的对象被构造时,它的构造函数按下面的顺序被调用(that the order of constructor calls for a complex object is as follows)
1.其基类(base-class)的构造函数被调用,这个步骤以递归的方式重复,所以最底层(the root of hierarchy)的构造函数首先被执行,然后是它上一层派生类(the next-derived class)...直到最顶层的派生类(the most-derived class).
The base-class constructor is called. This step is repeated recursively such that the root of the hierarchy is constructed first, followed by the next-derived class, etc., until the most-derived class is reached.)
2.如果有包含关系(composition),那么它的成员对象按照声明的顺序被构造.
Member initializers are called in the order of declaration.
3.派生类构造函数的内容(body)被执行.
The body of the derived-class constructor is called.
一个实例:
class Cake{
Cake(){System.out.println("Cake()");}
}
class Meal {
Meal() { System.out.println("Meal()"); }
}
class Bread {
Bread() { System.out.println("Bread()"); }
}
class Cheese {
Cheese() { System.out.println("Cheese()"); }
}
class Lettuce {
Lettuce() { System.out.println("Lettuce()"); }
}
class Lunch extends Meal {
Lunch() { System.out.println("Lunch()"); }
}
class PortableLunch extends Lunch {
//if make derived-class object as the menber of the base-class will lead a infinite
//loop and program will stop because of the memory consumed
//private Sandwich s=new Sandwich();
private Cake a=new Cake();
PortableLunch() {&n
相关文档:
在使用 Java™ 语言的泛型时,通配符非常令人困惑,并且最常见的一个错误就是在使用有界通配符的两种形式的其中之一(“? super T” 和 “? extends T”)时出现错误。您出错了吗?别沮丧,即使是专家也会犯这种错误,本月 Brian Goetz 将展示如何避免这个错误。
在 Java 语言中,数组是协变的( ......
package test;
import java.util.ArrayList;
import java.util.List;
import org.nuxeo.common.xmap.annotation.XNode;
import org.nuxeo.common.xmap.annotation.XNodeList;
import org.nuxeo.common.xmap.annotation.XObject;
/**
* Book 实体对象,此处用XMap注解
* @author Administra ......
Java 7提供了一个新API访问文件系统,但除此之外,JSR 203(NIO.2)还包含其它很多新特性,这个新版本的确新增了很多改善I/O编程的类,本文将会介绍下面的新特性:
· SeekableByteChannel:随机访问通道;
· MulticastChannel:允许IP多播的通道;
· NetworkChannel:新的网络通道超级接口;
· ......
1.新建了一个HelloWorld的JAVA Project 2.源文件放在SRC目录下,但是将图片文件 XX.GIF 放入该目录下在源文件中却不能使用相对路径,只能将图片文件放在HelloWorld 目录下面才可!可在类中类似使用 ImageIO.read(new File("XX.GIF")); ......
学了集合类,想用Java的集合类编一个通讯录,可是发现题目要对通讯录中的姓名和编号进行排序。
菜鸟刚刚学Java,本来还真不知道有比较器,嘿嘿,以为Java是如此强大,可以直接调用Sort()方法就可以对集合类中的对象进行排序,嘿嘿,于是便试了一下,太不好使了呀,嘿嘿,于是我看了看书,到网上查了查,原来要实现比较器的 ......