Java的构造函数

构造函数是

用于对象和字段初始化(即在变量声明时存储适当的值,使其处于“从一开始就具有有效值”的状态)的特殊方法。
它在生成对象(实例化)时自动调用,在生成类的对象时的时机(new 类名())下运行。

在创建实例时就可以赋值的好处是,由于会自动调用实例生成,所以可以事先定义变量,并且不需要调用另一个方法进行初始化,因此代码变得更简单。

构造函数也是一种方法,所以可以进行重载(即定义多个同名方法)。

class Student{
        :
  Student(String n){
        :
  }
  Student(String n, int e, int m){
        :
  }
}

定义构造函数的方法如下:
– 构造函数的名称与类名相同(因此名称的首字母大写)。
– 构造函数不返回任何值(也不写void)。
调用构造函数的方法如下:
– 在创建对象时,可以在“new 类名()”的括号内写入传递给构造函数的参数,以调用构造函数。

publec class Student{
        :
  Student(String n){
        :
  }
  Student(String n, int e, int m){
        :
  }
}
public static void main(String[] args){
    Student stu1 = new Student("菅原");
    Student stu2 = new Student("田仲", 75, 100);
           :
           :

如果在调用方将”菅原”作为对象stu1的参数传递,则在定义方会调用Student(String n)构造函数,并将其设置为变量。如果在对象stu2的参数中传递(“田仲”, 75, 100),则会调用Student(String n, int e, int m)构造函数,并将其设置为变量。

如果在类中没有编写构造函数,编译器会自动创建一个无参数的构造函数(代码本身不会改变)。这个被称为默认构造函数。

范文

构造函数之前

class StuSample3{
  public static void main(String[] args){
    Student3 stu1 = new Student3();
    Student3 stu2 = new Student3();

    stu1.setData("菅原");
    stu1.setScore(90, 80);
    stu1.display();

    stu2.setData("田仲", 75, 100);
    stu2.display();
  }
}
class Student3{
  String name;
  int engScore;
  int mathScore;

  void setData(String n){
    name = n;
  }
  void setData(String n, int e, int m){
    name = n;
    engScore = e;
    mathScore = m;
  }
  void setScore(int e, int m){
    engScore = e;
    mathScore = m;
  }
  void display(){
    System.out.println(name + "さん");
    System.out.println("英語" + engScore + "点・数学" + mathScore + "点");
  }
}

对象实例化之后

class StuSample3{
  public static void main(String[] args){
    Student3 stu1 = new Student3("菅原");
    Student3 stu2 = new Student3("田仲", 75, 100);

    stu1.setScore(90, 80);
    stu1.display();
    
    stu2.display();
  }
}
class Student3{
  String name;
  int engScore;
  int mathScore;

  Student3(String n){
    name = n;
  }
  Student3(String n, int e, int m){
    name = n;
    engScore = e;
    mathScore = m;
  }
  void setScore(int e, int m){
    engScore = e;
    mathScore = m;
  }
  void display(){
    System.out.println(name + "さん");
    System.out.println("英語" + engScore + "点・数学" + mathScore + "点");
  }
}
菅原さん
英語90点・数学80点
田仲さん
英語75点・数学100点

由于在构造函数之前创建对象并赋值,因此可能发生变量内容尚未设置(数据为空)的情况。空数据状态被认为是不好的,因此在生成实例的同时赋值的构造函数是方便且安全的代码,可以得到更易读的代码,以确定哪个值进入了哪个方法或对象。

请提供更多上下文信息。

 

广告
将在 10 秒后关闭
bannerAds