以下载自 Think in Java 4.0
都是很基础的知识:
阅读到本文底部之前先看看下面的代码会打印出什么样的结果:
1.
package com.testClass;
class Bowl{
Bowl(int i){
System.out.println("Bowl(" + i + ")");
}
void f1(int i){
System.out.println("f1(" + i + ")");
}
}
class Table{
static Bowl bowl1 = new Bowl(1);
Table(){
System.out.println("Table()");
bowl2.f1(1);
}
void f2(int i){
System.out.println("f2(" + i + ")");
}
static Bowl bowl2 = new Bowl(2);
}
class Cupboard {
Bowl bowl3 = new Bowl(3);
static Bowl bowl4 = new Bowl(4);
Cupboard(){
System.out.println("Cupboard()");
bowl4.f1(2);
}
void f3(int i){
System.out.println("f3(" + i + ")");
}
static Bowl bowl5 = new Bowl(5);
}
/**
* @author Jeelon
*/
public class TestB {
public static void main(String[] args) {
System.out.println("Creating new Cupboard() in main");
new Cupboard();
System.out.println("Creating new Cupboard() in main");
new Cupboard();
table.f2(1);
cupboard.f3(1);
}
static Table table = new Table();
static Cupboard cupboard = new Cupboard();
}
2.
package com.testClass;
class Super {
int i = 10;
public Super() {
print();
i = 20;
}
void print() {
System.out.println("super-"+i);
}
}
class Sub extends Super {
int j = 30;
Sub() {
print();
j = 40;
}
void print() {
System.out.println("sub-"+j);
}
public static void main(String args[]) {
System.out.println(new Sub().j);
}
}
3.
package com.testClass;
class Game{
Game(int i){
System.out.println("Game Constructor");
}
}
class BoardGame extends Game{
BoardGame(int i){
super(i);
System.out.println("BoardGame Constructor");
}
}
/**
*
* @author Jeelon
*
*/
public class TestExtends extends BoardGame{
TestExtends(){
super(11);
System.out.println("TestExtends Constructor");
}
public static void main(String[] args) {
new TestExtends();
}
}
1.Run Result:
/*
-----------载自Think in Java 4.0 静态变量的初始化。 运行结果:-----------------
Bowl(1)
Bowl(2)
Table()
f1(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f1(2)
f2(1)
f3(1)
-----------运行结果:-----------------*/
2.Run Result:
/*
-----------运行结果:-----------------
sub-0
sub-30
40
-----------运行结果:-----------------
结果显示:基类构造器,总会被调用,而且是在导出构造器之前被调用
*/
3.Run Result:
/*
-----------载自Think in Java 4.0构造器 运行结果:-----------------
Game Constructor
BoardGame Constructor
TestExtends Constructor
-----------运行结果:-----------------
结果显示和上例相同 :基类构造器,总会被调用,而且是在导出构造器之前被调用 ,编译器将会提醒你基类的构造器必须是你导出类构造器中要做的第一件事
如:把类中super(int i)去掉 则会报编译错误 ,因为将找不到符合父类Game()形式的构造器。
*/