Bird
0
0

You want to create a class Rectangle with fields width and height, and a method area() that returns the area. Which is the correct class definition?

hard📝 Application Q8 of 15
Java - Classes and Objects
You want to create a class Rectangle with fields width and height, and a method area() that returns the area. Which is the correct class definition?
Aclass Rectangle { int width, height; int area { return width * height; } }
Bclass Rectangle { int width, height; void area() { return width * height; } }
Cclass Rectangle { int width, height; int area() { return width * height; } }
Dclass Rectangle { int width, height; int area() { width * height; } }
Step-by-Step Solution
Solution:
  1. Step 1: Check method return type and syntax

    The method area() should return an int and use return keyword with expression.
  2. Step 2: Validate each option

    class Rectangle { int width, height; int area() { return width * height; } } correctly declares method returning int with return statement. class Rectangle { int width, height; void area() { return width * height; } } uses void but returns a value (error). class Rectangle { int width, height; int area { return width * height; } } misses parentheses for method. class Rectangle { int width, height; int area() { width * height; } } misses return statement.
  3. Final Answer:

    class Rectangle { int width, height; int area() { return width * height; } } -> Option C
  4. Quick Check:

    Methods returning values must declare return type and use return [OK]
Quick Trick: Use return type and return statement for methods returning values [OK]
Common Mistakes:
  • Using void but returning value
  • Missing parentheses in method
  • Omitting return keyword

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes