-1

I cant figure out the errors! But while compiling it shows error. Please help me out.....

// 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();
    }
}`
Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
  • You should call display() only after all of the 3 instance variables have been initialised. Or, alternatively, write 2 different display() methods for each area, OR initialise the 3 variables with default values. – Am_I_Helpful Dec 06 '15 at 08:20
  • 1
    Am_I_Helpful is right, in display you are working with all fields. – Dani Dec 06 '15 at 08:21
  • 1
    I recommend to have two different classes which extends `Area`. Or implements an interface for it. Depending on which constructor was invoked the class will behave differently. That is a sign that your class is in fact several classes. – Emz Dec 06 '15 at 08:24
  • What is the question? If the program doesn't do what you expect, change it. It appears you have simple not set the variables you use later. so set them. – Peter Lawrey Dec 06 '15 at 08:31
  • 2
    have a look over here: http://stackoverflow.com/questions/5076710/what-is-float-in-java – Aman Gupta Dec 06 '15 at 08:50
  • @MaheshwarLigade I'm not quite sure how C# constructor overloading is relevant to a question about java constructor overloading, especially since the overload isn't the actual problem.. – Vogel612 Dec 06 '15 at 12:55

2 Answers2

1

Use double instead of float.

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();
}
}
Anik Saha
  • 4,313
  • 2
  • 26
  • 41
0

As Anik mentioned, either change the constructor to take double as a parameter instead of float or while calling this constructor use suffix 4.5 with 'f' to specify that you want to pass float i.e., new area(4.5f);