• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Java Puzzle #8: Interfaces and Visibility

Contents

  • Answer
  • Explanation

What is the output of the following snippets:

Shape.java:

public interface Shape {
    public void draw();
    private void calculateArea();
    public void printArea();
}

Rectangle.java

public class Rectangle implements Shape {

    private final int x1, x2, y1, y2;
    private int area;

    public Rectangle(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.x2 = x2;
        this.y1 = y1;
        this.y2 = y2;
    }

    @Override
    public void calculateArea() {
        area = Math.abs((x1 - x2) * (y1 - y2));
    }

    @Override
    public void draw() {
        // TODO Auto-generated method stub
    }

    @Override
    public void printArea() {
        calculateArea();
        System.out.println("My area is " + area + ".");
    }

}

test.java:

public class test {
    public static void main(String[] args) {
        Shape s = new Rectangle(0, 0, 1, 1);
        s.printArea();
    }
}

. . . . . . . . . . . . . .

Answer

My area is 1.

Explanation

Interfaces may not implement anything. So it makes no sense to define private methods. Nevertheless it seems to be valid Java code.

Published

Aug 9, 2012
by Martin Thoma

Category

Code

Tags

  • Java 36
  • Programming 52
  • puzzle 22

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor