Java Little Knowledge

时间:2023-12-09 19:17:37

1.Constructor running order of Base class and Derived class

This is Alibaba's audition problem.

 class A{
     A(int x){
         System.out.println(x);
     }
 }
 class B{
     A m=new A(1);
     B(){
         m=new A(2);
     }
 }
 class C extends B{
     A n=new A(3);
     C(){
         n=new A(4);
     }
 }
 public class ali {
     public static void main(String[]args){
         new C();
     }
 }

output :

1

2

3

4

java Is different from C#.

java:Base class first

  Base class member define.

  Base class constructor

  Derived class member define.

  Derived class constructor.

C#:member define first

  Base class member define.

  Derived class member define.

  Base class constructor.

  Derived class constructor.

2.Derived class constructor will call Base class  constructor.

//子类的构造函数会调用父类构造函数
class one {
    public one(){
        System.out.println("one");
    }
}
class two extends one{
    public two (){
        System.out.println("two");
    }
    public two(String s){
        System.out.println("two "+s);
    }
}
class three extends two{
    public three(){
        this("haha");
        System.out.println("three");
    }
    public three(String s){
        super("haha");
        System.out.println("three "+s);
    }
}
public class Construct {
  public static void main(String[]args){
      new three();
  }
}

Java Little Knowledge

3.i++

Java Little Knowledge

4.

Java Little Knowledge

5.

Java Little Knowledge

6.接口继承

interface A{
    int n=3;
    void fun();
}
interface B{
    int n=3;//都是final类型的默认。
    void fun();
}
class C implements A,B{
    public C(){
        //n=4;//wrong ,ambiguous二义性
        //A.n=4;//wrong,final 类型不可赋值
    }
    public void fun(){//函数不会有二义性,只要有这个函数,就算实现了借口

    }
}
public class InterfaceTest {
    public static void main(String[]args){
        new C().fun();
    }
}