JAVA重難點問題剖析(二)

iteye_15500發表於2011-09-02


這次主要剖析以下問題:
抽象類與介面的區別、別名、區域性變數的語句塊作用域、this構造和super構造

一、抽象類與介面的區別:
* 1.抽象類中可以定義所有成員變數(含例項變數和靜態變數[含常量])和非空方法,而介面中只能定義常量和空方法;
* 2.抽象類在定義抽象方法時必須加abstract,而在介面中可以加但不需要加;
* 3.介面允許多繼承:一個介面可以基層多個介面,實現介面的類也可以繼承多個介面,但JAVA的類僅支援單繼承。

package test;

interface object1 {
// int var1;
//static int var1s;
int VAR1 = 2;// 介面中只能定義常量,等同於final static int VAR1=2;

int interfaceMethod1();
abstract int interfaceMethod2();//介面中的方法其實就是抽象方法,但在介面中一般不加abstract
// int inferfaceMethod3(){} 介面中不能含有非抽象方法
}
abstract class object2 {
int var2;
static int var2s;
final static int VAR2 = 2;//抽象類中可以定義變數也可以定義常量

abstract int abstractMethod1();
//int abstractMethod2();空方法必須加abstract修飾符
//abstract int abstractMethod3(){} 抽象方法不能指定方法體
void abstractMethod4(){}//抽象類中可以含有非抽象方法

}

二、下面中的引用變數都是別名
package test2;

public class test {
int a;

public test(int i) {
this.a = i;
}

public static void main(String[] args) {
test test1 = new test(10);
test test2 = test1;
System.out.println(test1.a);
System.out.println(test2.a);
test1 = null;
// System.out.println(test1.a);
System.out.println(test2.a);

}

}

三、區域性變數的語句塊作用域:
語句塊{}中所宣告的變數的作用域處在宣告該變數的語句塊中,語句塊外部不能訪問
public class hong {
public static void main(String[] args) {
int var1 = 1;
{
int var2 = 2;
}
System.out.println(var1);
// System.out.println(var2);
// var2不能別解析,因為var2的作用域處在語句塊{}中
}
}
四、this構造和super構造
二者必須位於建構函式的第一行,this()構造用於串鏈同一個類中的建構函式,而super()構造用於啟用超類的建構函式,如果建構函式的第一句不是this()構造或者super()構造,則會插入一條指向超類預設建構函式的super()呼叫


class test {
int i,j;
test(int i, int j) {
this.i = i;
this.j = j;
}
}

public class SuperDemo extends test {
int k,l;

SuperDemo() {
this(11,12);
}
/* 錯誤,插入插入一條指向超類預設建構函式的super()呼叫
SuperDemo(int i, int j) {
this.k = i;
this.l = j;
}
*/
public static void main(String[] args) {
SuperDemo sd = new SuperDemo();
System.out.print(sd.i+""+ sd.j+sd.k+sd.l);
}
}

相關文章