xeritt

Пример полиморфизма

Oct 21st, 2017
217
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package ru.company.app;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. interface IScreen {
  7.     void draw(int x, int y);
  8.     void put(int x, int y);
  9. }
  10.  
  11. abstract class Figure implements IScreen {
  12.     private int x;
  13.     private int y;
  14.  
  15.     @Override
  16.     public void put(int x, int y) {
  17.         this.x = x;
  18.         this.y = y;
  19.     }
  20. }
  21.  
  22. class Point extends Figure {
  23.     @Override
  24.     public void draw(int x, int y) {
  25.         put(x, y);
  26.         System.out.println(this.getClass().toString()+ " x=" + x + " y="+y);
  27.     }
  28. }
  29.  
  30. class Circle extends Figure/*Point*/ {
  31.     private int radius;
  32.     @Override
  33.     public void draw(int x, int y) {
  34.         put(x, y);
  35.         System.out.println(this.getClass().toString()+ " x=" + x + " y="+y + " radius="+radius);
  36.     }
  37. }
  38.  
  39. public class Main {
  40.     public static void main(String[] args) {
  41.         Point point = new Point();
  42.         point.draw(10, 10);
  43.  
  44.         Circle circle = new Circle();
  45.         circle.draw(20, 20);
  46.  
  47.         List<Figure> figures = new ArrayList<>();
  48.  
  49.         figures.add(point);
  50.         figures.add(circle);
  51.  
  52.         for (Figure curFig: figures) {
  53.             curFig.draw(10, 10);
  54.         }
  55.     }
  56. }
RAW Paste Data Copied