I've more over 4 years working with Java and today I've seen some piece of code that I thought at first glance it is invalid Java code. The code is:
Although, the following code is familiar to me:
Here I've defined a reference named "interests" of type "subclass to ArrayList" and I am overriding the "add" method in this subclass. So, I've re-looked at the first snippet again and could realize it to be:
As if I defined a class the following way:
Which Prints:
List<String> interests = new ArrayList<String>() {{ add("Java"); add("C#"); }};
List<String> interests = new ArrayList<String>() { @Override public void add(int index, String element) { // TODO Auto-generated method stub super.add(index, element); } };
List<String> interests = new ArrayList<String>() { // Anonymous initialization block (vs static init block) { add("Java"); add("C#"); } };
public class MyClass { { doSomeThing(); doSomeThing(); } void doSomeThing() { System.out.println("doing"); } public static void main(String[] args) { MyClass c = new MyClass(); } }
doing
doing
一楼用户回复:这些都是java的新用法
http://m-hewedy.blogspot.com/2012/02/strange-java-syntax-for-me-at-least.html