构造函数实例分析

来源:互联网 发布:淘宝与支付宝如何解绑 编辑:程序博客网 时间:2024/06/13 07:25

package zhangsan.lisi;

public class ChinaTest {
 public static void main(String [] args){
  
  Aclass a = new Aclass(1,2);
  Aclass b = new Aclass(5);
  a.show();
  b.show();
 }
}
class Aclass
{
 private int i = 99;
 public Aclass(int i ) {//无参构造函数
    //System.out.println("i="+i);输出的是i=5;
 this.i = i;//吧形参i发送给此刻正在创建对象的成员了
 }
 public Aclass(int a,int b) {//有参构造函数
 this.i = a + b;//this在构造方法中 代表了该方法本次运行所创建的那个新对象
 }
 public void show()
 {
  //System.out.println("a + b = "+ a + b);
  System.out.println("i = "+ this.i);//在构造方法中代表方法的调用者,即本次调用了该方法的对象
 }
}

原创粉丝点击