[关闭]
@XQF 2017-02-15T17:11:20.000000Z 字数 1133 阅读 1272

有意思的Java代码

java

1.main方法

  1. class A {
  2. public static void main(String[] args) {
  3. for (String str : args) {
  4. System.out.println(str);
  5. }
  6. }
  7. }
  8. public class Ac {
  9. public static void main(String[] args) {
  10. String[] strs = "I am XQF".split(" ");
  11. A.main(strs);
  12. }
  13. }

2.在main方法前输出

  1. public class Ac {
  2. static {
  3. System.out.println("没有进入main方法");
  4. }
  5. public static void main(String[] args) {
  6. }
  7. }

3.与构造方法名字相同的成员方法

  1. class T {
  2. public T() {
  3. System.out.println("T constructor!");
  4. }
  5. public void T() {
  6. System.out.println("Call T ");
  7. }
  8. }
  9. public class Test {
  10. public static void main(String[] args) {
  11. T t = new T();
  12. t.T();
  13. }

结果,说明这样是没毛病,只是不建议

T constructor!
Call T

4.陷阱覆盖重载陷阱

首先,方法名字相同,即有可能是重载也有可能是覆盖。

说他是覆盖,但是返回类型也不一样。
说他是重载,但是参数列表又同样是空。

所以都不是,。,。
要改成覆盖,就应该使返回类型相同,
要改成重载,就应该其具有不同的参数列表

返回类型不能作为任何判断依据

  1. class T {
  2. public int print() {
  3. return 1;
  4. }
  5. }
  6. public class Test extends T {
  7. public float print() {
  8. return 2f;
  9. }
  10. public static void main(String[] args) {
  11. T t = new Test();
  12. System.out.println(t.print());
  13. }
  14. }

5.自定义label跳出多重循环

  1. public static void main(String[] args) {
  2. int a = 0;
  3. out:
  4. for (int i = 0; i < 100; i++) {
  5. for (int j = 0; j < 100; j++) {
  6. if (j == 5) {
  7. a = j;
  8. break out;
  9. }
  10. }
  11. }
  12. System.out.println("Over");
  13. System.out.println("a:" + a);
  14. }

结果

Over
a:5
Java中保留goto关键字,为了将来可能会加入。这种标签跳出看上去好像很好用似的。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注