Bird
0
0

Find the error in this code snippet:

medium📝 Debug Q7 of 15
Java - Interfaces
Find the error in this code snippet:
interface Shape {
    double area();
}

class Circle implements Shape {
    double radius;
    Circle(double r) { radius = r; }
    public double area() { return 3.14 * radius * radius; }
}

class Test {
    public static void main(String[] args) {
        Shape s = new Circle(5);
        System.out.println(s.radius);
    }
}
ACannot access radius through Shape reference.
BCircle class must declare area() as static.
CInterface methods cannot return double.
DCircle constructor must be public.
Step-by-Step Solution
Solution:
  1. Step 1: Understand reference type access

    Reference of type Shape cannot access Circle-specific fields like radius.
  2. Step 2: Identify cause of error

    Accessing s.radius causes compile error because radius is not in Shape interface.
  3. Final Answer:

    Cannot access radius through Shape reference. -> Option A
  4. Quick Check:

    Interface reference limits access to interface members = C [OK]
Quick Trick: Interface references access only interface methods/fields [OK]
Common Mistakes:
  • Expecting access to class fields via interface reference
  • Thinking interface methods must be static
  • Believing interface methods cannot return primitives

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes