二、类的构造方法(阶段三)

--通过一个类创建一个对象,这个过程叫做实例化
--实例化是通过调用构造方法(又叫做构造器)实现的

一、什么是构造方法?

方法名和类名一样(包括大小写)
没有返回类型
实例化一个对象的时候,必然调用构造方法

public class Test{
   // 方法名和类名一样(包括大小写)
   // 没有返回类型
   public Test(){
       System.out.println("实例化一个对象,必然调用构造方法")
   }

   public static void main(String[] args){
        //实例化一个对象的时候,必然调用构造方法
        Test test=new Test();
   }

}

二、隐式的构造方法

Test的构造方法是

public Test(){
}

这个无参的构造方法,如果不写,就会默认提供一个

public class Test{
   //这个无参的构造方法,如果不写,
   //就会默认提供一个无参的构造方法
  // public Test(){
   //    System.out.println("实例化一个对象,必然调用构造方法")
   //}
}

三、有参的构造方法

一旦提供了一个有参的构造方法
同时又没有显式的提供一个无参的构造方法
那么默认的无参的构造方法,就“木有了“

public class Test{
   String num;
   //有参的构造方法
   //默认的无参的构造方法就失效了
   public Test(String num){
       this.num=num;
   }

   public static void main(String[] args){
        Test test1=new Test("测试");
        
        Test test=new Test(); //无参的构造方法“木有了”
   }

}

四、构造方法的重载

和普通方法一样,构造方法也可以重载

public class Test{
   String name;
   int num;
   //带一个参数的构造方法了
   public Test(int num){
       this.num=num;
   }
   //带两个参数的构造方法
   public Test(int num,String name){
       this.num=num;
       this.name=name;
   }

   public static void main(String[] args){
        Test test1=new Test(1,"测试");
        Test test=new Test(2); 
   }

}
原文地址:https://www.cnblogs.com/rozen-lin/p/14325905.html