构造函数未被识别

  • 本文关键字:识别 构造函数 java
  • 更新时间 :
  • 英文 :


当我运行程序时,我得到:构造函数Package()是未定义的,构造函数insurredpackage()也是未定义的类Package和insurredpackage工作得很好,没有问题,这是给我麻烦的主要原因。Package a = new Package();and InsuredPackage b = new InsuredPackage();强调。

import java.io.*;
import java.util.*;
public class homework06
{
public static void main(String[] args)
{
ArrayList<String> simple = new ArrayList<String>();
ArrayList<String> insured = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
boolean bool = true;
while(bool == true)
{
System.out.println("Choose Option:");
System.out.printf("1. Simple Packagen2. Insured Packagen3. Exitn");
int x = sc.nextInt();
if(x == 1)
{
Package a = new Package();
a.id = sc.next();
a.weight = sc.nextDouble();
}
else if(x == 2)
{
InsuredPackage b = new InsuredPackage();
b.id = sc.next();
b.weight = sc.nextDouble();
}
else if(x == 3)
{
bool = false;
}
}
sc.close();
}    
}
public class Package
{
String id;
double weight;
public Package(String id,double weight)
{
this.id = id;
this.weight = weight;
}
public String getID()
{  
return id;
}
public double getW()
{
return weight;
}
public double computeCost()
{
double charge=0;
if(weight>0 && weight<=3)
{
charge = 3;
}
else if(weight>3)
{
charge = 3 + (0.7*(weight-3));
}
return charge;
}
public String toString()
{
return id + "," + weight + "," + computeCost();
}
}
public class InsuredPackage extends Package
{    
public InsuredPackage(String id,double weight)
{
super(id,weight);
}
public double computeCostExtra()
{
double extra=0;
double charge = computeCost();
if(charge>0 && charge<=5)
{
extra = 2;
}
else if(charge>5 && charge<=10)
{
extra = 3;
}
else if(charge>10)
{
extra = 5;
}
return charge + extra;
}

public String toString()
{
return id + "," + weight + "," + computeCostExtra();
}
}

如果您没有在类中声明任何默认构造函数,则Java将创建默认构造函数。默认构造函数为无参数构造函数。

InsuredPackagePackage类中,您已经创建了带参数的构造函数。因此,java将不会创建默认构造函数,而您已经在代码中调用了无参数构造函数。

InsuredPackage b = new InsuredPackage();

Package a = new Package();

你需要在你的类中创建无参数构造函数.

当你添加带参数的构造函数时,java不会考虑默认的无参数构造函数,除非显式指定。它会抛出错误。您要么需要添加构造函数,要么需要传递@cheenu回答中提到的参数。

最新更新