Add a code snippet for anonymous classes (BAEL-2833) (#6690)
* Add a code snippet about anonymous classes (BAEL-2833) Add a code snippet about anonymous classes (BAEL-2833) Create module core-java-2 and move 'anonymous' package there * Adjust the pom of core-java-8-2 module * Adjust unit test
This commit is contained in:
committed by
maibin
parent
c18f588f28
commit
34c0cbe8e3
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.anonymous;
|
||||
|
||||
public class Book {
|
||||
|
||||
final String title;
|
||||
|
||||
public Book(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String description() {
|
||||
return "Title: " + title;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.anonymous;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Code snippet that illustrates the usage of anonymous classes.
|
||||
*
|
||||
* Note that use of Runnable instances in this example does not demonstrate their
|
||||
* common use.
|
||||
*
|
||||
* @author A. Shcherbakov
|
||||
*
|
||||
*/
|
||||
public class Main {
|
||||
|
||||
public static void main(String[] args) {
|
||||
final List<Runnable> actions = new ArrayList<Runnable>(2);
|
||||
|
||||
Runnable action = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("Hello from runnable.");
|
||||
}
|
||||
|
||||
};
|
||||
actions.add(action);
|
||||
|
||||
Book book = new Book("Design Patterns") {
|
||||
@Override
|
||||
public String description() {
|
||||
return "Famous GoF book.";
|
||||
}
|
||||
};
|
||||
|
||||
System.out.println(String.format("Title: %s, description: %s", book.title, book.description()));
|
||||
|
||||
actions.add(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println("Hello from runnable #2.");
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
int count = 1;
|
||||
|
||||
Runnable action2 = new Runnable() {
|
||||
static final int x = 0;
|
||||
// static int y = 0;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
System.out.println(String.format("Runnable with captured variables: count = %s, x = %s", count, x));
|
||||
}
|
||||
};
|
||||
actions.add(action2);
|
||||
|
||||
for (Runnable a : actions) {
|
||||
a.run();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class UnitTest {
|
||||
/**
|
||||
* Stub test
|
||||
*/
|
||||
@Test
|
||||
public void givenPreconditions_whenCondition_shouldResult() {
|
||||
assertTrue(true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user