Lesson 2

Colloquium – Object-Oriented Programming

An example colloquium with a solution.

Task

There are classes: A, B, C. A is an abstract class that requires implementing random() method that returns pseudorandom number. B and C extends A. In C class there is a field int max which represents the upper limit for a random number. This field can be modified only be a constructor.


Additionally, there are two interfaces: D and E. D contains all the methods from E. Each from the interfaces contains maximum one method. F class implements D interface, so it contains methods sum(int x, double y) and sum(double x, int y). A purpose of those methods is to sum up numbers given as the arguments and return the result as double type. Only one of those methods can sum the numbers.


Create one object for both classes C and F and anonymous implementation of D interface. Present a behavior of each created method/constructor in the main method.


Solution can be found below.

Solution

abstract class A {
  abstract int random();
}

class B extends A {

  int random() {
      return (int)(Math.random() * 1000);
  }
}

class C extends A {

  private int max;

  C(int max) {
      this.max = max;
  }

  int random() {
      return (int)(Math.random() * (max + 1));
  }
}

interface D extends E {

  double sum(int x, double y);
}

interface E {

  double sum(double x, int y);
}

class F implements D {

  public double sum(int x, double y) {
      return sum(y, x);
  }

  public double sum(double x, int y) {
      return x + y;
  }
}

public class Main {
  public static void main(String[] args) {
      C c = new C(500);
      System.out.println(c.random());
      F f = new F();
      System.out.println(f.sum(100.0, 10));
      System.out.println(f.sum(10, 100.0));
      E e = new E() {

          public double sum(double x, int y) {
              return x + y;
          }
      };
      System.out.println(e.sum(100.0, 10));
  }
}