java继承和构造函数
其显示错误如下:java继承和构造函数,java,Java,其显示错误如下: class A{ int ax;int ay; A(int x, int y){ ax=x; ay=y; } void show(){ System.out.println("value of Ax is : "+ax+" value of Ay is : "+ay); } } class B extends A{ int bx,by; B(int bx,int by){
class A{
int ax;int ay;
A(int x, int y){
ax=x;
ay=y;
}
void show(){
System.out.println("value of Ax is : "+ax+" value of Ay is : "+ay);
}
}
class B extends A{
int bx,by;
B(int bx,int by){
this.bx=bx;
this.by=by;
}
void show(){
super.show();
System.out.println("Value of Bx is : "+bx+" value of By is : "+by);
}
}
public class progl2q2{
public static void main(String s\[\]){
A m=new A(10,20);
B b=new B(20,30);
m.show();
b.show();
}
}
在java中,如果为类创建参数化构造函数,则不会创建默认构造函数。在这里,您有一个类a的参数化构造函数,但您的类B的构造函数没有调用a的参数化构造函数,而是尝试调用一个没有参数的构造函数,在这种情况下,该构造函数不存在 要解决此问题,您可以在a中创建非参数化构造函数,也可以简单地更改B类构造函数,如:
progl2q2.java:36: error: constructor A in class A cannot be applied to given types;
A m=new A(10,20);
^
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
1 error
C:\Users\Labuser\Desktop\saurabh\prog list2>
您已经在类A中定义了构造函数。类B在扩展类A时必须调用构造函数中的super()。类B应该类似于:
B(int bx,int by){
super(4,5);//or any numbers you want as parameters of A's constructor
this.bx=bx;
this.by=by;
}
class B extends A {
int bx, by;
B(int x, int y) {
//pass any value for super class
//if you do not want user super() remove constructor in class A
super(0, 1);
this.bx = x;
this.by = y;
}
void show() {
System.out.println("Value of Bx is : " + bx + " value of By is : " + by);
}
}
并修复您的主要方法,如下所示:
B(int bx,int by){
super(4,5);//or any numbers you want as parameters of A's constructor
this.bx=bx;
this.by=by;
}
class B extends A {
int bx, by;
B(int x, int y) {
//pass any value for super class
//if you do not want user super() remove constructor in class A
super(0, 1);
this.bx = x;
this.by = y;
}
void show() {
System.out.println("Value of Bx is : " + bx + " value of By is : " + by);
}
}
您在构造函数中遇到了问题 在您编写的程序中,B扩展了A,您没有A的默认构造函数,而是将A的构造函数参数化,这是错误的 当您为一个类创建变量时,如果该类扩展了其他类,那么它的构造函数将首先初始化,但在您的情况下,无法初始化父类的构造函数,因此程序将失败 因此,解决方案是,您可以在类中有一个默认构造函数,或者您需要从B调用参数化构造函数 这是第一个解决方案
public static void main(String[] args) {
}
以下是输出:::
Ax值为:10 Ay值为:20
Ax的值为:0 Ay的值为:0
Bx值为:20 By值为:30
正如您在初始化B对象时所看到的,已经调用了构造函数
这是第二个解决方案:
class A {
int ax;
int ay;
public A() {
super();
}
A(int x, int y) {
ax = x;
ay = y;
}
void show() {
System.out.println("value of Ax is : " + ax + " value of Ay is : " + ay);
}
}
class B extends A {
int bx, by;
B(int bx, int by) {
this.bx = bx;
this.by = by;
}
void show() {
super.show();
System.out.println("Value of Bx is : " + bx + " value of By is : " + by);
}
}
public class test {
public static void main(String s[]) {
A m = new A(10, 20);
B b = new B(20, 30);
m.show();
b.show();
}
}
欢迎来到堆栈溢出!请查看我们的,以帮助您提出一个好问题,从而得到一个好答案。如果您的main方法有问题,请将其更正为public static void main(String args[])@PramodYadav,我认为代码被错误/草率地复制。您确定上面的代码实际上就是您运行的代码吗?