Advertisement
irmantas_radavicius

Untitled

May 8th, 2025
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.76 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. // Shape.java
  4.  
  5. // We decide we want to build an app that contains
  6. // different Shapes. What is common is all objects
  7. // are shapes, but what is different is the shapes
  8. // are different, each have their own attributes
  9. // (to be modeled as fields) and behaviour (meaning,
  10. // different method implementations)
  11.  
  12. // we declare the class as abstract thus forbidding
  13. // to create objects of this type, which means,
  14. // we intend this class to be extended. Inheritance
  15. // ("extension") would mean that we will derive another
  16. // class from this base class, which means we will copy
  17. // (almost) everything and then add/change something, as
  18. // we desire
  19.  
  20. abstract class Shape implements Comparable<Shape> {
  21.    
  22.     // common attribute for all the classes
  23.     private String type;
  24.    
  25.     // unique to Shape as constructors are not inheritted,
  26.     // every class has its own constructor(s), but can
  27.     // call/use constructors of base/parent/superclasses
  28.    
  29.     public Shape(String type){
  30.         this.type = type;
  31.     }
  32.    
  33.     // we implement this as an example how we can make
  34.     // the class sortable, i.e. we don't write a sorting
  35.     // algorithm, because it is already done in Collections.sort
  36.     // but we need to provide a comparator which would
  37.     // explain how we want to sort a new type, in this case,
  38.     // Shape, and we say inside that when comparing Shapes
  39.     // we simply compare their types, which are strings for
  40.     // which compareTo is already implemented in Java,
  41.     // i.e. we build on already existing functionality
  42.    
  43.     public int compareTo(Shape shape){
  44.         return type.compareTo(shape.type);
  45.     }
  46.  
  47.     public String getType(){
  48.         return type;
  49.     }
  50.    
  51.     // we could return 0, but this is just a dummy value
  52.     // which does not make sense and is there just as a
  53.     // "filler" which we try to avoid (eg. constructors
  54.     // requiring values rather than having 0, "empty" etc
  55.     // thus we declare the method as abstract meaning
  56.     // derived classes will have to implement it or also
  57.     // will stay abstract
  58.    
  59.     public abstract double getArea();
  60. }
  61.  
  62. // Square.java
  63.  
  64. class Square extends Shape {
  65.    
  66.     // we provide an atrribute/field which
  67.     // is unique to Square
  68.    
  69.     private double length;
  70.    
  71.     // we provide a unique constructor,
  72.     // which in the first line calls appropriate
  73.     // constructor from a base class, using keyword
  74.     // "super" and then supplying the parameters,
  75.     // it has to be the first line of the constructor;
  76.     // note that we can also call multiple constructors
  77.     // from the same class to avoid duplication, using
  78.     // keyword "this"
  79.    
  80.     public Square(double length){
  81.         super("Square");
  82.         this.length = length;
  83.     }
  84.    
  85.     // override/implement an abstract method
  86.     // with a specific algorithm and thus the class
  87.     // becomes concrete, i.e. stops being abstract
  88.     // and since it is not declared abstract and has not
  89.     // abstract methods, an object can be created
  90.    
  91.     public double getArea(){
  92.         return length*length;
  93.     }
  94.    
  95. }
  96.  
  97. // Circle.java
  98.  
  99. class Circle extends Shape {
  100.  
  101.     // we do the same thing for Circle,
  102.     // simply the implementation/details/specifics
  103.     // are different, i.e. base/parent/superclasses
  104.     // specifies what is common/stable, and derived/child/subclass
  105.     // specifies what is changing/specific/different
  106.     // and we have a single base class and multiple
  107.     // derived classes thus constituting a hierarchy
  108.    
  109.     private double radius;
  110.    
  111.     public Circle(double radius){
  112.         super("Circle");
  113.         this.radius = radius;
  114.     }
  115.    
  116.     public double getArea(){
  117.         return 2 * Math.PI * radius;
  118.     }
  119.    
  120. }
  121.  
  122. // Main.java
  123.  
  124. // this is an alternative way of sorting, i.e. instead
  125. // of providing a stable/main version of comparing Shapes
  126. // we can decide there are multiple ways, and thus split
  127. // the functionality among multiple Comparators, each of
  128. // which implements Comparator<T> and does it differently,
  129. // and when we sort we supply the required implementation,
  130. // one of many, i.e. when we find a changing/unstable aspect,
  131. // we delegate it to a separate class thus following the
  132. // idea of modular programming, i.e. like Lego, changing one
  133. // block/brick into another without the need to change the
  134. // whole project
  135.  
  136. class AreaComparator implements Comparator<Shape> {
  137.    
  138.     public int compare(Shape s1, Shape s2){
  139.         if(s1.getArea() < s2.getArea())
  140.             return -1;
  141.         else if(s1.getArea() == s2.getArea())
  142.             return 0;
  143.         else
  144.             return 1;
  145.  
  146.     }      
  147. }
  148.  
  149.  
  150. public class Main {
  151.    
  152.     public static void main(String [] args){
  153.        
  154.         // note that a reference/pointer of the parent/ancestor
  155.         // can reference to any child/successor
  156.         // in the same hierarchy (also true for interfaces)
  157.         // because any child IS also an instance of a parent,
  158.         // can have more functionality or can change the existing
  159.         // implementations by overriding already inherited methods
  160.         // but it cannot delete them - it means some implementation
  161.         // will always be available if we call it, compared to otherwise,
  162.         // when we would call the method from a child which was added
  163.         // and would not be available in a parent, what then?
  164.        
  165.         //Shape shape = new Shape("Square");
  166.         //Shape square = new Square(2);
  167.         //Shape circle = new Circle(1);
  168.  
  169.         // and this would constitute as an example of
  170.         // (subtype) polymorphism, i.e. we write .getArea()
  171.         // the interface is the same, but implementations are
  172.         // different and one is picked based on which object
  173.         // we have created; i.e. we use the reference of the
  174.         // type Shape, but because it points to the instances
  175.         // of Square/Circle, the corresponding implementation
  176.         // from Square/Circle are used, thus resulting in
  177.         // polymorphic behaviour - same line has "many forms",
  178.         // i.e. looks the same but acts differently`
  179.  
  180.         //System.out.println(shape.getArea());
  181.         //System.out.println(square.getArea());
  182.         //System.out.println(circle.getArea());
  183.        
  184.         // and now we demonstrate how we use Shape as
  185.         // an abstraction, leaving details for derived classes
  186.         // avoiding switch or if/else statements and
  187.         // the need to know the exhaustive list of all the
  188.         // subtypes; subtypes can be added later by writing
  189.         // new classes, and the code does not need to know/change -
  190.         // it will be handled by polymorphic behaviour
  191.        
  192.         ArrayList<Shape> list = new ArrayList<Shape>();
  193.        
  194.         // we generate some data to put into our list
  195.        
  196.         Random r = new Random();
  197.         for(int i = 0; i < 10; ++i){
  198.             int temp = r.nextInt();
  199.             if(temp%2 == 0){
  200.                 list.add(new Circle(Math.abs(r.nextInt()%10)));
  201.             } else {
  202.                 list.add(new Square(Math.abs(r.nextInt()%10)));
  203.             }          
  204.         }
  205.        
  206.         // and now we just sort, i.e. we use a comparator,
  207.         // and the comparator calls getArea, and getArea used
  208.         // depends on the specific object in question,
  209.         // i.e. Square computes area differently than Circle;
  210.         // and we don't care, we don't need to know, it is the
  211.         // responsibility of the Square/Circle, and here we
  212.         // care about something else, i.e. we need to sort and
  213.         // we don't need to know the details, we just say -
  214.         // sort the list using AreaComparator, list is responsible
  215.         // for storage, and the comparator is responsible for
  216.         // order, and the .sort is responsible for the sorting
  217.         // algorithm; those can change independently, and we don'temp
  218.         // care because one does not need to know about the otherwise
  219.         // - this is the essence of the principle of information hiding
  220.         // which is the essence of what quality in the code means
  221.        
  222.         Collections.sort(list, new AreaComparator());
  223.        
  224.         // and now we print, again, getType is the same of all
  225.         // and getArea is different depending on the object, but
  226.         // the list does not know, thus we witness polymorphism
  227.         // again, in the full glory
  228.        
  229.         for(int i = 0; i < list.size(); ++i){
  230.             System.out.print(list.get(i).getType());
  231.             System.out.println(" " + list.get(i).getArea());
  232.         }
  233.        
  234.        
  235.     }
  236.    
  237. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement