[英]I am facing problem in using this constructor
Can anyone tell me, what is the mistake that i made in using "this" constructor, inside the constructor public Student().谁能告诉我,我在构造函数 public Student() 中使用“this”构造函数时犯了什么错误。 Please tell me how to correct it.
请告诉我如何纠正它。 Compiler is showing this error -
编译器显示此错误 -
Error:(10, 11) java: constructor Student in class com.shreyansh.Student cannot be applied to given types;错误:(10, 11) java: class com.shreyansh.Student 中的构造函数 Student 不能应用于给定类型; required: no arguments found: int,java.lang.String reason: actual and formal argument lists differ in length
必需:未找到 arguments:int,java.lang.String 原因:实际参数列表和形式参数列表的长度不同
****The code is shown here**** ****代码显示在这里****
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);
}
}
When you call a constructor from another constructor, you must define the constructor you are calling:当你从另一个构造函数调用一个构造函数时,你必须定义你正在调用的构造函数:
Adding this constructor:添加此构造函数:
public Student(int rno, String name) {
this.rno = rno;
this.name = name;
}
will allow the将允许
this(0, "Not defined");
call to pass compilation.调用通过编译。
public Student() {
this(0, "Not defined"); //what is the error in this line
}
What that tries to do, is call a constructor in the same class, with those parameters.尝试做的是使用这些参数在同一个 class 中调用构造函数。 In order for that to work, this constructor must be there:
为了让它工作,这个构造函数必须在那里:
public Student (int rno, String name) {
this.rno = rno;
this.name = name;
}
but you don't have such a constructor, so change your current constructor to:但是您没有这样的构造函数,因此将当前的构造函数更改为:
public Student() {
this.rno = 0;
this.name = "Not defined";
}
or, add the second constructor.或者,添加第二个构造函数。
When you are using this
inside your constructor, you are calling another constructor inside your class, but you don't actually have any other constructor that has such arguments, so you should create another constructor with said parameters like this:当您在构造函数中使用
this
时,您正在调用 class 中的另一个构造函数,但实际上您没有任何其他具有此类 arguments 的构造函数,因此您应该创建另一个具有上述参数的构造函数,如下所示:
public Student(int rno, String name)
{
this.rno = rno;
this.name;
}
the problem is the way you creating your object.问题是您创建 object 的方式。 your constructor must be like:
你的构造函数必须像:
public Student() {
// you have to indicate the value of each variable here
this.rno = 0;
this.name = "name";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.