java interview classic questions

1

public class Test1 {
  public static void main(String[] args) {
    int i = 1;
    i = i++;
    int j = i++;
    int k = i + ++i * i++;
    System.out.println("i=" + i);
    System.out.println("j=" + j);
    System.out.println("k=" + k);
  }
}

 Output result:

2

public class Father {
  private int i = test();
  private static int j = method();

  static {
    System.out.print("(1)");
  }

  Father() {
    System.out.print("(2)");
  }

  {
    System.out.print("(3)");
  }

  public int test() {
    System.out.print("(4)");
    return 1;
  }

  public static int method() {
    System.out.print("(5)");
    return 1;
  }
}

public class Son extends Father {
  private int i = test();
  private static int j = method();

  static {
    System.out.print("(6)");
  }

  Son() {
    System.out.print("(7)");
  }

  {
    System.out.print("(8)");
  }

  public int test() {
    System.out.print("(9)");
    return 1;
  }

  public static int method() {
    System.out.print("(10)");
    return 1;
  }

  public static void main(String[] args) {
    Son s1 = new Son();
    System.out.println();
    Son s2 = new Son();
  }
}

Output result:

3 The difference between local variables and member variables 

Method rewriting rules

  • The parameter list must be exactly the same as the method being overridden.

  • The return type and the return type of the overridden method can be different, but it must be a derived class of the return value of the parent class (the return type of java5 and earlier versions must be the same, and the return type of java7 and later versions can be different).

  • The access authority cannot be lower than the access authority of the overridden method in the parent class. For example: if a method of the parent class is declared as public, then overriding the method in the child class cannot be declared as protected.

  • The member methods of the parent class can only be overridden by its subclasses.

  • A method declared as final cannot be overridden.

  • A method declared as static cannot be overridden, but it can be declared again.

  • If the subclass and the superclass are in the same package, the subclass can override all methods of the superclass, except for the methods declared as private and final.

  • The subclass and the parent class are not in the same package, so the subclass can only override the non-final methods declared as public and protected of the parent class.

  • The overridden method can throw any non-mandatory exception, regardless of whether the overridden method throws an exception. However, the overridden method cannot throw a new mandatory exception, or a broader mandatory exception than the one declared by the overridden method, and vice versa.

  • The construction method cannot be overridden.

  • If you cannot inherit a method, you cannot override this method.

 

Guess you like

Origin blog.csdn.net/zheng_chang_wei/article/details/106926893