0
点赞
收藏
分享

微信扫一扫

Strange Java syntax (for me at least)--怪异的Java语法

闲云困兽 2022-08-18 阅读 71

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: 

List<String> interests = new ArrayList<String>() {{
add("Java");
add("C#");
}};

 

Although, the following code is familiar to me: 

List<String> interests = new ArrayList<String>() {
@Override
public void add(int index, String element) {
// TODO Auto-generated method stub
super.add(index, element);
}
};

 

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: 

List<String> interests = new ArrayList<String>() {

// Anonymous initialization block (vs static init block)
{
add("Java");
add("C#");
}
};

 

As if I defined a class the following way: 

public class MyClass {

{
doSomeThing();
doSomeThing();
}

void doSomeThing() {
System.out.println("doing");
}

public static void main(String[] args) {
MyClass c = new MyClass();
}
}

 

Which Prints: 

doing
doing

 

一楼用户回复:这些都是java的新用法

​​http://m-hewedy.blogspot.com/2012/02/strange-java-syntax-for-me-at-least.html​​

举报

相关推荐

0 条评论