Skip to content

Commit 0b9bb44

Browse files
dupirefrdaoire
authored andcommitted
[BAEL-2020] Differences between final, finally and finalize in Java (eugenp#4848)
* [BAEL-2020] Examples code * [BAEL-2020] Moving classes into 'keywords' package
1 parent 924a3dc commit 0b9bb44

5 files changed

Lines changed: 90 additions & 0 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baeldung.keywords.finalize;
2+
3+
public class FinalizeObject {
4+
5+
@Override
6+
protected void finalize() throws Throwable {
7+
System.out.println("Execute finalize method");
8+
super.finalize();
9+
}
10+
11+
public static void main(String[] args) throws Exception {
12+
FinalizeObject object = new FinalizeObject();
13+
object = null;
14+
System.gc();
15+
Thread.sleep(1000);
16+
}
17+
18+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.keywords.finalkeyword;
2+
3+
public final class Child extends Parent {
4+
5+
@Override
6+
void method1(int arg1, final int arg2) {
7+
// OK
8+
}
9+
10+
/* @Override
11+
void method2() {
12+
// Compilation error
13+
}*/
14+
15+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package com.baeldung.keywords.finalkeyword;
2+
3+
/*public class GrandChild extends Child {
4+
// Compilation error
5+
}*/
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.keywords.finalkeyword;
2+
3+
public class Parent {
4+
5+
int field1 = 1;
6+
final int field2 = 2;
7+
8+
Parent() {
9+
field1 = 2; // OK
10+
// field2 = 3; // Compilation error
11+
}
12+
13+
void method1(int arg1, final int arg2) {
14+
arg1 = 2; // OK
15+
// arg2 = 3; // Compilation error
16+
}
17+
18+
final void method2() {
19+
final int localVar = 2; // OK
20+
// localVar = 3; // Compilation error
21+
}
22+
23+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package com.baeldung.keywords.finallykeyword;
2+
3+
public class FinallyExample {
4+
5+
public static void main(String args[]) throws Exception {
6+
try {
7+
System.out.println("Execute try block");
8+
throw new Exception();
9+
} catch (Exception e) {
10+
System.out.println("Execute catch block");
11+
} finally {
12+
System.out.println("Execute finally block");
13+
}
14+
15+
try {
16+
System.out.println("Execute try block");
17+
} finally {
18+
System.out.println("Execute finally block");
19+
}
20+
21+
try {
22+
System.out.println("Execute try block");
23+
throw new Exception();
24+
} finally {
25+
System.out.println("Execute finally block");
26+
}
27+
}
28+
29+
}

0 commit comments

Comments
 (0)