【问题标题】:Constructor Overloading Error [duplicate]构造函数重载错误[重复]
【发布时间】:2015-12-06 06:48:50
【问题描述】:

我无法找出错误!但是在编译时显示错误。请帮帮我......

// This program is used to find the area of a circle and a rectangle    
// through constructor overloading concept.

class area {
    float radius;
    int l , b;
    public area(float r) {
        radius=r;
    }
    public area(int a , int d) {
        l=a;
        b=d;
    }
    public void display() {
        System.out.println("Area of Circle is = "+(3.14*radius*radius));
        System.out.println("Area of Rectangle is = "+(l*b));
    }
}

class constadd {
    public static void main(String arr[]) {
        area c = new area(4.5);
        c.display();
        area e=new area(4,5);
        e.display();
    }
}`

【问题讨论】:

  • 只有在所有 3 个实例变量都已初始化后,才应调用 display()。或者,或者,为每个区域编写 2 个不同的 display() 方法,或者用默认值初始化 3 个变量。
  • Am_I_Helpful 是对的,显示您正在处理所有字段。
  • 我建议有两个不同的类来扩展Area。或者为它实现一个接口。根据调用的构造函数,类的行为会有所不同。这表明您的班级实际上是几个班级。
  • 问题是什么?如果程序没有达到您的预期,请更改它。看来您没有设置稍后使用的变量。所以设置它们。

标签: java constructor overloading


【解决方案1】:

使用双精度而不是浮点数。

import java.util.*;
import java.lang.*;
import java.io.*;


class area {
double radius;
int l , b;
public area(double r) {
    radius=r;
}
public area(int a , int d) {
    l=a;
    b=d;
}
public void display() {
    System.out.println("Area of Circle is = "+(3.14*radius*radius));
    System.out.println("Area of Rectangle is = "+(l*b));
}
}

class  Ideone {
    public static void main(String arr[]) {
    area c = new area(4.5);

    c.display();
     area e=new area(4,5);
    e.display();
}
}

【讨论】:

    【解决方案2】:

    正如 Anik 提到的,要么将构造函数更改为将 double 作为参数而不是浮点数,要么在调用此构造函数时使用带 'f' 的后缀 4.5 来指定您要传递浮点数,即 new area(4.5f);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      相关资源
      最近更新 更多