Nikki Agarwal Nikki Agarwal - 3 years ago 115
Java Question

Tester Class Constructor Error

This is the homework question I have to answer: Implement a class

SodaCan
whose constructor receives the height and diameter or the soda can. Supply methods
getVolume
and
getSurfaceArea
. Supply a
SodaCanTester
class that tests your class.

This is the code I have for the
SodaCan
class.

public class SodaCan
{
private double Height;
private double Radius;

public SodaCan(double h, double d) {
Height = h;
Radius = d/2;
}

public double getVolume()
{
return Math.PI * Height * Math.pow(Radius, 2);
}

public double getSurfaceArea()
{
return (2 * Math.PI * Radius * Height) +
(2 * Math.PI * Math.pow(Radius, 2));
}
}


This is the code I have for the
SodaCanTester
class.

public class SodaCanTester
{
public static void main(String[] args)
{
SodaCan cylinder = new SodaCan();
cylinder.enterHeight(5);
cylinder.enterRadius(8);
System.out.println("Volume: " + getVolume());
System.out.println("Expected Volume: 1005.31");
System.out.println("Surface Area: " + getSurfaceArea());
System.out.println("Expected Surface Area: 653.45");
}
}


When I try to compile the tester class, I get an error with the constructor:

SodaCan cylinder = new SodaCan();


That says:


"constructor SodaCan in class SodaCan cannot be applied to given types".


What am I doing wrong, and how can I fix this?

Answer Source

Because, you have have args constructor in your class SodaCan

public SodaCan(double h, double d) {
    Height = h;
    Radius = d/2;
}

You need to explicitly declare no-arg constructor, if you want to make the below code work

SodaCan cylinder = new SodaCan();

Edited==

Your code should look like this

public SodaCan(double h, double d) {
    Height = h;
    Radius = d/2;
}

public SodaCan(){}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download