Concept explainers
Sections 11.2–11.4
11.1 (The Triangle class) Design a class named Triangle that extends GeometricObject. The class contains:
■ Three double data fields named side1, side2, and side3 with default values 1.0 to denote three sides of a triangle.
■ A no-arg constructor that creates a default triangle.
■ A constructor that creates a triangle with the specified side1, side2, and side3.
■ The accessor methods for all three data fields.
■ A method named getArea() that returns the area of this triangle.
■ A method named getPerimeter() that returns the perimeter of this triangle.
■ A method named toString() that returns a string description for the triangle.
For the formula to compute the area of a triangle, see
return "Triangle: side1 = " + side1 + " side2 = " + side2 + " side3 = " + side3;
Draw the UML diagrams for the classes Triangle and GeometricObject and implement the classes. Write a test program that prompts the user to enter three sides of the triangle, a color, and a Boolean value to indicate whether the triangle is filled. The program should create a Triangle object with these sides and set the color and filled properties using the input. The program should display the area, perimeter, color, and true or false to indicate whether it is filled or not.
Program Plan:
- Include the required import statement.
- Define the main class.
- Define the main method using public static main.
- Declare the input scanner.
- Get the three sides of the triangle from the user.
- Create an object for the “Triangle” class.
- Get the color from the user and call the “setColor” method with the parameter “color”.
- Get the Boolean value for filled the triangle and call the “setFilled” method with the parameter “filled”.
- Display the output.
- Define the main method using public static main.
- Define the “GeometricObject” class.
- Declare the required variables.
- Define the default constructor and constructor for the class.
- Define the accessor and matator.
- The “isFilled” and “setColor” method will return the value to the main class.
- Define the derived class “Triangle” from the “GeometricObject” class.
- Declare the required variables.
- Define the default constructor and constructor for the class.
- Define the accessor.
- The “getArea()” method will calculate the area of triangle and then return the result.
- The “getPerimeter()” method will return the perimeter of the triangle.
- The “toString()” method will return the three sides of the triangle.
The below program is used to display the area, perimeter and sides of the triangle as follows:
Explanation of Solution
Program:
//import statement
import java.util.Scanner;
//class Excersise11_01
public class Exercise11_01
{
// main method
public static void main(String[] args)
{
// declare the scanner variable
Scanner input = new Scanner(System.in);
//get the input from the user
System.out.print("Enter three sides: ");
//declare the variables
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
//create an object for the "Triangle" class
Triangle triangle = new Triangle(side1, side2, side3);
//get the input from the user
System.out.print("Enter the color: ");
String color = input.next();
//call the "setColor" function
triangle.setColor(color);
//get the input from the user
System.out.print("Enter a boolean value for filled: ");
boolean filled = input.nextBoolean();
//call the "setFilled" function
triangle.setFilled(filled);
//print the output
System.out.println("The area is " + triangle.getArea());
System.out.println("The perimeter is "
+ triangle.getPerimeter());
System.out.println(triangle);
}
}
//definition of class "GeometricObject"
class GeometricObject
{
/* declare the required variables and initialize it */
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
//definition of default constructor
public GeometricObject()
{
//create an object
dateCreated = new java.util.Date();
}
//definition of constructor
public GeometricObject(String color, boolean filled)
{
//create an object
dateCreated = new java.util.Date();
//set the value
this.color = color;
this.filled = filled;
}
//definition of accessor
public String getColor()
{
//return the color
return color;
}
//definition of mutator
public void setColor (String color)
{
//set the color
this.color = color;
}
//definition of the "isFilled" method
public boolean isFilled()
{
//return the value
return filled;
}
//definition of the "setFilled" method
public void setFilled(boolean filled)
{
//set the value
this.filled = filled;
}
//definition of the "getDateCreated" method
public java.util.Date getDateCreated()
{
//return the value
return dateCreated;
}
//definition of the "toString" method
public String toString()
{
//return the value
return "created on " + dateCreated + "\ncolor: " + color + " and filled: " + filled;
}
}
//definition of derived class "Triangle"
class Triangle extends GeometricObject
{
/* declare the required variables and initialize it */
private double side1 = 1.0, side2 = 1.0, side3 = 1.0;
/*definition of Constructor */
public Triangle()
{
}
/* definition of Constructor */
public Triangle(double side1, double side2, double side3)
{
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
//definition of accessor
public double getSide1()
{
//return the value
return side1;
}
//definition of accessor
public double getSide2()
{
//return the value
return side2;
}
//definition of accessor
public double getSide3()
{
//return the value
return side3;
}
/*override method of "getArea" in GeometricObject */
public double getArea()
{
//declare and calculate the value
double s = (side1 + side2 + side3) / 2;
//return the value
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
/*override method of "getPerimeter" in GeometricObject */
public double getPerimeter()
{
//return the value
return side1 + side2 + side3;
}
//definition of "toString" method
public String toString()
{
// return the three sides
return "Triangle: side1 = " + side1 + " side2 = " + side2 +" side3 = " + side3;
}
}
UML diagram:
Explanation:
The above UML diagram the “GeometricObject” is a parent class which contains “color”, “filled”, “dateCreated” variables and “GeometricObject()”, “GeometricObject(String color, boolean filled)”, “getColor()”, “getColor(String color)”, “isFilled()”, “setFilled(boolean filled)”, “getDateCreated()” and “toString()” methods.
The “Triangle” is the child class extended from “GeometricObject” class it contains “side1”, “side2” and “side3” variables and “Triangle()”, “Triangle(double side1, double side2, double side3)”, “getSide1()”, “getSide2()”, “getSide3()”, “getArea()”, “getPerimeter()” and “toString()” methods.
Enter three sides: 2
3
4
Enter the color: black
Enter a boolean value for filled: true
The area is 2.9047375096555625
The perimeter is 9.0
Triangle: side1 = 2.0 side2 = 3.0 side3 = 4.0
Want to see more full solutions like this?
Chapter 11 Solutions
Introduction to Java Programming and Data Structures, Comprehensive Version (11th Edition)
Additional Engineering Textbook Solutions
Database Concepts (8th Edition)
Computer Science: An Overview (13th Edition) (What's New in Computer Science)
Starting Out with C++ from Control Structures to Objects (9th Edition)
Elementary Surveying: An Introduction To Geomatics (15th Edition)
Starting Out with Python (4th Edition)
Introduction To Programming Using Visual Basic (11th Edition)
- JAVA 2 LANGUAGE 8.2 (The Stock class) Following the example of the Circle class in Section 8.2, design a class named Stock that contains: ■ A string data field named symbol for the stock’s symbol. ■ A string data field named name for the stock’s name. ■ A double data field named previousClosingPrice that stores the stock price for the previous day. ■ A double data field named currentPrice that stores the stock price for the current time. ■ A constructor that creates a stock with the specified symbol, name, previousClosingPrice, and currentPrice. ■ A method named getChangePercent() that returns the percentage changed from previousClosingPrice to currentPrice. The formula to be used is (currentPrice - previousClosingPrice) / previousClosingPrice. Draw the UML diagram for the class and then implement the class (write the code for the class). Write a test program (application) in which you create a Stock object stock1 with the stock symbol ORCL, the name Oracle Corporation, the…arrow_forwardColorful bubbles In this problem, you will use the Bubble class to make images of colorful bubbles. You will use your knowledge of classes and objects to make an instance of the Bubble class (aka instantiate a Bubble), set its member variables, and use its member functions to draw a Bubble into an image. Every Bubble object has the following member variables: X coordinate Y coordinate Size (i.e. its radius) Color Complete main.cc Your task is to complete main.cc to build and draw Bubble objects based on user input. main.cc already does the work to draw the Bubble as an image saved in bubble.bmp. You should follow these steps: First, you will need to create a Bubble object from the Bubble class. Next, you must prompt the user to provide the following: an int for the X coordinate, an int for the Y coordinate, an int for the Bubble's size, and a std::string for the Bubble's color. Next, you must use the user's input to set the new Bubble object's x and y coordinates, the size, and the…arrow_forwardGoal 1: Update the Fractions Class ADD an implementation that takes an integer as a parameter. The functionality remains the same: Instead of multiplying/dividing the current object with another Fraction, it multiplies/divides with an integer. For example; a fraction 2/3 when multiplied by 4 becomes 8/3. Similarly, a fraction 2/3 when divided by 4 becomes 1/6. Goal 2: Update the Recipe Class Add a private member variable of type int to denote the serving size and initialize it to 1. Update the overloaded extraction operator (<<) to include the serving size. New Member functions to the Recipe Class: 1. Add four member functions get the value of each of the member variable of the Recipe class: getRecipeName(), getIngredientNames(), getIngredientQuantities(), getServingSize() They return the value of the respective member variables. 2. Add and implement a member function that scales the current recipe to a new serving size. The signature of this function is: void scaleRecipe(int…arrow_forward
- Create a class: Question 1 with data members: 1D integer array of maximum size: 100, n (int). Create a dynamic constructor which takes input of n and n no. of array elements. Apart from taking input this class also displays the maximum and minimum elements from the given array elements.arrow_forwardDesign a class named StopWatch. The class contains:■■ Private data fields startTime and endTime with getter methods.■■ A no-arg constructor that initializes startTime with the current time.■■ A method named start() that resets the startTime to the current time.■■ A method named stop() that sets the endTime to the current time.■■ A method named getElapsedTime() that returns the elapsed time for thestopwatch in milliseconds.Draw the UML diagram for the class then implement the class. Write a test programthat measures the execution time of sorting 100,000 numbers using selection sort.arrow_forwardPart 1. Create a Parent Class Create a complete Java class that can be used to create a Computer object as described below: A Computer has-a: Мапufacturer Disk Size Manufacturing Date Number of cores a) Add all instance variables (data encapsulation is expected) b) The class must have getters and setters for all instance variables c) The class must have two constructors, a no-arg and a constructor that receives input parameters for each instance variable. d) Implement toString() method for your classarrow_forward
- Java code please 1. Appliance and TV by CodeChum Admin Create a class called Appliance. An appliance simply has a: brand (a text) a cost (a monetary value) a power status (ON or OFF) Power status, brand and cost should not be accessible out the class or its hierarchy of inheritance. It has one constructor that accepts a string and double for the brand and cost respectively (prints "Appliance Constructor" as well). It sets the power status to OFF. Apart from the getters, it also has two public methods, power(), and toString(). power() turns on the appliance if it is off, otherwise, if it is on, it turns the appliance off. toString() simple returns a String object representing the Appliance in this format ("Brand: xxxx, Cost: PhP xxxx.xx, Power: xx"). Create another class called Television. Television is an Appliance. It only has the following additional private attributes: type (whether Smart or Non-Smart) volume (0 - 100) channel (1 - 100) It should have the following…arrow_forward2-) Write a superclass encapsulating a rectangle. A rectangle has two attributes representing the width and the height of the rectangle as a data members. It has methods returning the perimeter(P=2*(L+W)) and the area of the rectangle(A=L*W). This class has a subclass encapsulating a parallelepiped, or box. A parallelepiped has a rectangle as its base, and another attribute named depth. The derived class Box should have a constructor, a volume() function and an override function named area () that returns the surface area of the box. Include the classes constructed in a working C++ program. Have your program call all the member functions in each class and verify the results manually.arrow_forwardPart 1: Design and implement a class called Sphere that contains instance data that represents the sphere's diameter. The Sphere also includes the following: • A constructor to accept and initialize the diameter, • A default constructor to initialize sphere's diameter to 1, A copy constructor getter and setter methods for the diameter • Methods that o calculate and return the volume and surface area of the sphere o A toString method that returns a one-line description of the sphere to include diameter, Surface Area and Volume o An equals method to compare diameters of the spheres and if they are the same the spheres are identical otherwise not. Needed formulas: 4. ar where r = Radius and Radius = Diameter / 2 3. • volume %3D %3D • Surface area = 4 nr Where r = Radius %3D 'art 2: reate a driver class called MultiSphere, whose main method instantiates and updates several Sphere objects and prints them to the onitor. - the toolhar press AIT+F10 (PCor ALT+EN+F10 (Mac) Save and Submit to…arrow_forward
- Python Quadrilaterals Write a program that accepts the dimensions of a quadrilateral and prints itscorresponding area and perimeter. PROGRAM DESIGNYou are provided the 2 python files: (1) Quadrilateral.py which contains the parent classQuad and (2) input.py which contains all input mechanisms and conditions that wouldhandle taking in inputs and initializing object instances. You are not allowed to edit thesefiles.The Quad class represents a quadrilateral, which is a four-sided polygon. It has thefollowing attributes: top, bottom, left and right. These attributes have the float datatype.Aside from these attributes, the constructor and printResults are also found within classQuad. Quad- top- bottom- left- right+ printResults() Calling Quad’s printResults() – prints the area and perimeter of a rectangle. Given thatthe top and bottom dimensions are equal – and the left and right dimension are equal aswell. – Otherwise, it prints ‘Syntax Error!’. Your task is to create another file with…arrow_forwardIn a course, a teacher gives the following tests and assignments:• A lab activity that is observed by the teacher and assigned a numeric score.• A pass/fail exam that has 10 questions. The minimum passing score is 70.• An essay that is assigned a numeric score.• A final exam that has 50 questionsWrite a class named CourseGrades . The class should have a member named gradesthat is an array of GradedActivity pointers. The grades array should have four ele-ments, one for each of the assignments previously described. The class should have thefollowing member functions:setLab : This function should accept the address of a GradedActivityobject as its argument. This object should already hold the stu-dent’s score for the lab activity. Element 0 of the grades arrayshould reference this object.setPassFailExam : This function should accept the address of a PassFailExamobject as its argument. This object should already hold the stu-dent’s score for the pass/fail exam. Element 1 of the grades…arrow_forwardThe base class Pet has attributes name and age. The derived class Dog inherits attributes from the base class Pet class and includes a breed attribute. Complete the program to: Create a generic pet, and print the pet's information using print_info(). Create a Dog pet, use print_info() to print the dog's information, and add a statement to print the dog's breed attribute. class Pet:def __init__(self):self.name = ''self.age = 0 def print_info(self):print('Pet Information:')print(' Name:', self.name)print(' Age:', self.age) class Dog(Pet):def __init__(self):Pet.__init__(self) self.breed = '' my_pet = Pet()my_dog = Dog() pet_name = input()pet_age = int(input())dog_name = input()dog_age = int(input())dog_breed = input() # TODO: Create generic pet (using pet_name, pet_age) and then call print_info() # TODO: Create dog pet (using dog_name, dog_age, dog_breed) and then call print_info() # TODO: Use my_dog.breed to output the breed of the dogarrow_forward
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTMicrosoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,