In: Computer Science
Create an application that uses a constructor and two different methods.
JAVA
Java Console Application that calculates area of a square:
import java.util.Scanner;
//Class definition
class Square
{
//Private instance variable
private double side;
//Default Constructor
public Square()
{
//Set side value
setSide(1.0);
}
//Argument Constructor
public Square(double tSide)
{
//Set side value
setSide(tSide);
}
//Set method for side
public void setSide(double tSide)
{
//Set side value
side = tSide;
}
//Get method for side
public double getSide()
{
//Get side value
return side;
}
//Computing area
public double computeArea()
{
//Computing area
return side*side;
}
//Returning string version
public String toString()
{
return "Square Side: " + side + "
\t Area of the Square: " + computeArea();
}
}
//Driver class
public class SquareTest
{
// set up GUI components and instantiate new
MyRectangle
public static void main( String args[] )
{
Scanner input = new Scanner(
System.in );
// create a new Square with no
initial values
Square square = new Square();
System.out.print( "Please enter
a double value for the side of the square: " );
double double1 =
input.nextDouble();
square.setSide( double1 );
System.out.println( square ); // see the results of the test
} // end main
} // end class SquareTest
____________________________________________________________________________________________
Sample Run: