Kotlin Class: Student class with promotion eligibility check
Write a Kotlin program that creates a class 'Student' with properties for name, age, and grade. Include a function to check if the student is eligible for promotion.
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. It can contain properties (variables) and functions (methods) that operate on those properties.
- Constructors: In Kotlin, a primary constructor is defined in the class header and is used to initialize the properties of an object.
- Conditional Statements: The if statement is used to check conditions and return different values based on those conditions.
- Boolean Return Type: A function that returns a boolean (true or false) can be used to make decisions.
- String Interpolation: The $variable syntax allows you to insert variable values directly into a string.
Hints (Try Before Looking at the Solution!)
Try to solve the problem with these hints:
- Hint 1: Create a class called Student with properties for name, age, and grade.
- Hint 2: Define a function inside the class that checks if the grade is 8 or higher.
- Hint 3: The function should return true if the grade is 8 or higher, otherwise return false.
- Hint 4: In the main() function, create instances of the Student class with different grades.
- Hint 5: Use println() to display whether each student is eligible for promotion.
Sample Solution:
Kotlin Code:
class Student(val name: String, val age: Int, val grade: Int) {
fun isEligibleForPromotion(): Boolean {
return grade >= 8
}
}
fun main() {
val student1 = Student("Ema Luella", 16, 9)
val student2 = Student("Iclza Iqoqtux", 15, 7)
println("${student1.name} is eligible for promotion: ${student1.isEligibleForPromotion()}")
println("${student2.name} is eligible for promotion: ${student2.isEligibleForPromotion()}")
}
Sample Output:
Ema Luella is eligible for promotion: true Iclza Iqoqtux is eligible for promotion: false
Explanation:
In the above exercise -
- First we define a class "Student" with three properties: name, age, and grade. The class also includes a function isEligibleForPromotion() that checks if the student's grade is greater than or equal to 8. If the grade is 8 or higher, the function returns true; otherwise, it returns false.
- In the main() function, we create two instances of the Student class, student1 and student2, with different names, ages, and grades. Each student object is then checked for promotion eligibility by calling the isEligibleForPromotion() function.
Kotlin Editor:
Previous: Create and display Car information.
Next: Book class with display function.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics