关键字: java 面试题 final finally finalize
public class FinalTest {
// 在定义时初始化
public final int A = 10;
public final int B;
// 在初始化块中初始化
{
B = 20;
}
// 非静态final变量不能在静态初始化块中初始化
// public final int C;
// static {
// C = 30;
// }
// 静态常量,在定义时初始化
public static final int STATIC_D = 40;
public static final int STATIC_E;
// 静态常量,在静态初始化块中初始化
static {
STATIC_E = 50;
}
// 静态变量不能在初始化块中初始化
// public static final int STATIC_F;
// {
// STATIC_F = 60;
// }
public final int G;
// 静态final变量不可以在构造器中初始化
// public static final int STATIC_H;
// 在构造器中初始化
public FinalTest() {
G = 70;
// 静态final变量不可以在构造器中初始化
// STATIC_H = 80;
// 给final的变量第二次赋值时,编译会报错
// A = 99;
// STATIC_D = 99;
}
// final变量未被初始化,编译时就会报错
// public final int I;
// 静态final变量未被初始化,编译时就会报错
// public static final int STATIC_J;
}
class ParentClass {
public final void TestFinal() {
System.out.println("父类--这是一个final方法");
}
}
public class SubClass extends ParentClass {
/**
* 子类无法重写(override)父类的final方法,否则编译时会报错
*/
// public void TestFinal() {
// System.out.println("子类--重写final方法");
// }
public static void main(String[] args) {
SubClass sc = new SubClass();
sc.TestFinal();
}
}
public final class FinalTest {
int i = 10;
public static void main(String[] args) {
FinalTest ft = new FinalTest();
ft.i = 99;
System.out.println(ft.i);
}
}
public final class FinallyTest {
public static void main(String[] args) {
try {
throw new NullPointerException();
} catch (NullPointerException e) {
System.out.println("程序抛出了异常");
} finally {
System.out.println("执行了finally语句块");
}
}
}
public final class FinallyTest {
// 测试return语句
public ReturnClass testReturn() {
try {
return new ReturnClass();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("执行了finally语句");
}
return null;
}
// 测试continue语句
public void testContinue() {
for (int i = 0; i < 3; i++) {
try {
System.out.println(i);
if (i == 1) {
continue;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("执行了finally语句");
}
}
}
// 测试break语句
public void testBreak() {
for (int i = 0; i < 3; i++) {
try {
System.out.println(i);
if (i == 1) {
break;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("执行了finally语句");
}
}
}
public static void main(String[] args) {
FinallyTest ft = new FinallyTest();
// 测试return语句
ft.testReturn();
System.out.println();
// 测试continue语句
ft.testContinue();
System.out.println();
// 测试break语句
ft.testBreak();
}
}
class ReturnClass {
public ReturnClass() {
System.out.println("执行了return语句");
}
}
protected void finalize() throws Throwable { }
public final class FinallyTest {
// 重写finalize()方法
protected void finalize() throws Throwable {
System.out.println("执行了finalize()方法");
}
public static void main(String[] args) {
FinallyTest ft = new FinallyTest();
ft = null;
System.gc();
}
}
Runtime.getRuntime().gc();
public static void runFinalizersOnExit(boolean value) {
//other code
}