【问题标题】:I am facing problem in using this constructor我在使用这个构造函数时遇到问题
【发布时间】:2020-04-16 08:41:07
【问题描述】:

谁能告诉我,我在构造函数内部使用“this”构造函数时犯了什么错误 公共学生()。请告诉我如何纠正它。编译器显示此错误 -

错误:(10, 11) java: com.shreyansh.Student 类中的构造函数 Student 不能应用于给定类型; 必需:无参数 找到:int,java.lang.String 原因:实际参数列表和形式参数列表的长度不同

****此处显示代码****

package com.shreyansh;

import java.util.Scanner;

public class Student {
      private int rno;
      private String name;

      public Student() {
          this(0, "Not defined"); //what is the error in this line
      }

      public void enter() {
          System.out.println("Enter name of the student - ");
          Scanner scanner = new Scanner(System.in);
          this.name=scanner.nextLine();
          System.out.println("Enter the roll number - ");
          this.rno=scanner.nextInt();
          scanner.close();
      }
      public void show() {
          System.out.println("The name of the student is - "+name);
          System.out.println("And the roll number is - "+rno);
      }
}

【问题讨论】:

  • 在构造函数中调用this(..) 意味着你调用了另一个构造函数。但是您要调用的那个不存在。 Student 类没有将 int 和 String 作为参数的构造函数。
  • 没有带两个参数的构造函数。你需要定义它。

标签: java constructor


【解决方案1】:

当你从另一个构造函数调用一个构造函数时,你必须定义你正在调用的构造函数:

添加这个构造函数:

public Student(int rno, String name) {
    this.rno = rno;
    this.name = name;
}

将允许

this(0, "Not defined");

调用以传递编译。

【讨论】:

    【解决方案2】:
    public Student() {
              this(0, "Not defined"); //what is the error in this line
          }
    

    尝试做的是使用这些参数调用同一个类中的构造函数。为了让它工作,这个构造函数必须在那里:

    public Student (int rno, String name) {
      this.rno = rno;
      this.name = name;
    }
    

    但是你没有这样的构造函数,所以把你当前的构造函数改成:

    public Student() {
      this.rno = 0;
      this.name = "Not defined";
    }
    

    或者,添加第二个构造函数。

    【讨论】:

      【解决方案3】:

      当您在构造函数中使用this 时,您正在调用类中的另一个构造函数,但实际上您没有任何其他具有此类参数的构造函数,因此您应该创建另一个具有上述参数的构造函数,如下所示:

      public Student(int rno, String name) 
      {
         this.rno = rno;
         this.name;
      }
      

      【讨论】:

        【解决方案4】:

        问题在于您创建对象的方式。 你的构造函数必须是这样的:

        public Student() {
               // you have to indicate the value of each variable here
              this.rno = 0; 
              this.name = "name";
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-07-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-11
          • 1970-01-01
          相关资源
          最近更新 更多