[BAEL-2020] Differences between final, finally and finalize in Java (#4848)

* [BAEL-2020] Examples code

* [BAEL-2020] Moving classes into 'keywords' package
This commit is contained in:
François Dupire 2018-08-14 08:26:57 +02:00 committed by daoire
parent 924a3dc9cc
commit 0b9bb44781
5 changed files with 90 additions and 0 deletions

View File

@ -0,0 +1,18 @@
package com.baeldung.keywords.finalize;
public class FinalizeObject {
@Override
protected void finalize() throws Throwable {
System.out.println("Execute finalize method");
super.finalize();
}
public static void main(String[] args) throws Exception {
FinalizeObject object = new FinalizeObject();
object = null;
System.gc();
Thread.sleep(1000);
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.keywords.finalkeyword;
public final class Child extends Parent {
@Override
void method1(int arg1, final int arg2) {
// OK
}
/* @Override
void method2() {
// Compilation error
}*/
}

View File

@ -0,0 +1,5 @@
package com.baeldung.keywords.finalkeyword;
/*public class GrandChild extends Child {
// Compilation error
}*/

View File

@ -0,0 +1,23 @@
package com.baeldung.keywords.finalkeyword;
public class Parent {
int field1 = 1;
final int field2 = 2;
Parent() {
field1 = 2; // OK
// field2 = 3; // Compilation error
}
void method1(int arg1, final int arg2) {
arg1 = 2; // OK
// arg2 = 3; // Compilation error
}
final void method2() {
final int localVar = 2; // OK
// localVar = 3; // Compilation error
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.keywords.finallykeyword;
public class FinallyExample {
public static void main(String args[]) throws Exception {
try {
System.out.println("Execute try block");
throw new Exception();
} catch (Exception e) {
System.out.println("Execute catch block");
} finally {
System.out.println("Execute finally block");
}
try {
System.out.println("Execute try block");
} finally {
System.out.println("Execute finally block");
}
try {
System.out.println("Execute try block");
throw new Exception();
} finally {
System.out.println("Execute finally block");
}
}
}