Java Little Knowledge

Java类构造顺序与接口继承
本文探讨了Java中基类与派生类构造函数的运行顺序,以及接口继承的特性,通过实例代码展示了Java与C#的区别。

1.Constructor running order of Base class and Derived class

This is Alibaba's audition problem.

 1 class A{
 2     A(int x){
 3         System.out.println(x);
 4     }
 5 }
 6 class B{
 7     A m=new A(1);
 8     B(){
 9         m=new A(2);
10     }
11 }
12 class C extends B{
13     A n=new A(3);
14     C(){
15         n=new A(4);
16     }
17 }
18 public class ali {
19     public static void main(String[]args){
20         new C();
21     }
22 }

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();
  }
}

3.i++

4.

5.

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();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值