java 构造器调用构造器_初学Java,在构造器中调用另一个构造器(十)

  • Post author:
  • Post category:java


在Java中在构造器中调用另一个构造器,和C#的写法有又那么一点点的不同

public class Apple

{

public String name;

public String color;

public String weight;

public Apple()

{}

//两个参数构造器

public Apple(String name,String color,double weight)

public static void main(String[] args)

{

//通过this调用另一个重载的构造器的初始代码

this(name,color);

//下面this引用该构造器正在初始化的Java对象

this.weight = weight;

}

}

C#是这样的,写在方法签名中

public class MyClass

{

private int _Age;

private string _Name;

public MyClass( string Name):this( Name, 20 )

{}

public MyClass( string Name, int Age )

{

_Age = Age;

_Name = Name;

}

}两都使用了this关键字

如果是调用父类构造器,语法的差别也是类似,Java用super,C#用base

public class Apple

{

public String name;

public String color;

public String weight;

public Apple()

{}

//两个参数构造器

public Apple(String name,String color,double weight)

public static void main(String[] args)

{

//通过this调用另一个重载的构造器的初始代码

super(name,color);

//下面this引用该构造器正在初始化的Java对象

this.weight = weight;

}

public class MyClass

{

private int _Age;

private string _Name;

public MyClass( string Name):base( Name, 20 )

{}

public MyClass( string Name, int Age )

{

_Age = Age;

_Name = Name;

}

}



版权声明:本文为weixin_35373786原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。