Java - Top-Level Class Used as the Superclass for a Local Class

Description

Top-Level Class Used as the Superclass for a Local Class

Demo

import java.util.Random;

class RandomInteger {
  protected Random rand = new Random();

  public int getValue() {
    return rand.nextInt();
  }//from  w w  w.j a  v a 2s  .c  om
}

class RandomLocal {
  public RandomInteger getRandomInteger() {
    // Local inner class that inherits RandomInteger class
    class RandomIntegerLocal extends RandomInteger {
      @Override
      public int getValue() {
        int n1 = rand.nextInt();
        return n1;
      }
    }
    return new RandomIntegerLocal();
  } 
}

public class Main {
  public static void main(String[] args) {
    // Generate random integers using the RandomInteger class
    RandomInteger rTop = new RandomInteger();
    System.out.println("Random integers using Top-level class:");
    System.out.println(rTop.getValue());
    System.out.println(rTop.getValue());
    System.out.println(rTop.getValue());

    // Generate random integers using the RandomIntegerLocal class
    RandomLocal local = new RandomLocal();
    RandomInteger rLocal = local.getRandomInteger();
    System.out.println("\nRandom integers using local inner class:");
    System.out.println(rLocal.getValue());
    System.out.println(rLocal.getValue());
    System.out.println(rLocal.getValue());
  }
}

Result

Related Topic