w3resource

Kotlin Class: Circle class with circumference calculation


Write a Kotlin program that creates a class 'Circle' with properties for radius and center coordinates. Include a function to calculate the circle circumference.


Pre-Knowledge (Before You Start!)

Before attempting this exercise, you should be familiar with the following concepts:

  • Classes in Kotlin: A class is a blueprint for creating objects with specific properties and functions.
  • Primary Constructor: It initializes the properties of an object when an instance of the class is created.
  • Mathematical Constants: Kotlin provides PI from kotlin.math, which represents the mathematical constant π (pi).
  • Arithmetic Operations: Understanding how to use multiplication in Kotlin to compute formulas.
  • Functions: Functions inside a class can perform specific calculations, such as computing the circumference of a circle.

Hints (Try Before Looking at the Solution!)

Try to solve the problem with these hints:

  • Hint 1: Create a class called Circle with properties for radius, centerX, and centerY.
  • Hint 2: Define a function named calculateCircumference() inside the class.
  • Hint 3: Use the formula 2 * PI * radius to calculate the circumference.
  • Hint 4: Import kotlin.math.PI to use the π constant in your calculation.
  • Hint 5: In the main() function, create an instance of the Circle class with a given radius and center coordinates.
  • Hint 6: Call the calculateCircumference() function on the created object and print the result.

Sample Solution:

Kotlin Code:

import kotlin.math.PI

class Circle(
    val radius: Double,
    val centerX: Double,
    val centerY: Double
) {
    fun calculateCircumference(): Double {
        return 2 * PI * radius
    }
}

fun main() {
    val circle = Circle(7.0, 0.0, 0.0)
    val circumference = circle.calculateCircumference()
    println("Circle Circumference: $circumference")
}

Sample Output:

Circle Circumference: 43.982297150257104

Explanation:

In the above exercise -

  • First we define a class "Circle" with three properties: radius, centerX, and centerY. The class includes a function calculateCircumference that calculates and returns the circle circumference using the formula 2 *π *radius. This is the mathematical constant PI.
  • In the "main()" function, we create an instance of the Circle class named circle with a radius of 5.0 and center coordinates at (0.0, 0.0). We then call the "calculateCircumference()" function on the circle object and store the result in the circumference variable. Finally, we print the calculated circumference.

Kotlin Editor:


Previous: BankAccount class with deposit and withdrawal functions.
Next: Employee class with details display.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.