0Pricing
Java Academy · Lesson

Polymorphic Behaviors

Use polymorphism to print, sort, and aggregate mixed shapes. Keep algorithms tiny and easy to read for mobile.

Polymorphic Behaviors is a free Java Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Overview

Polymorphic behaviors let us treat all shapes the same while each runs its own math. We will: (1) print a mixed list uniformly, (2) sort by area, and (3) compute totals with one loop.

Base API checklist

Base API keeps the actions used everywhere:

  • area() and perimeter() — must be implemented by each shape.
  • Optional tiny helper like label() or info() for neat printing.
  • Keep fields inside concrete shapes.

Code: uniform print

Uniform print: the loop uses only the Shape API. Each object runs its own implementation for the math.

public class Main {
  static abstract class Shape {
    abstract double area();
    abstract double perimeter();
    String label() { return getClass().getSimpleName(); }
    String info() { return String.format("area=%.2f, per=%.2f", area(), perimeter()); }
  }
  static class Circle extends Shape {
    double r; Circle(double r) { this.r = (r < 0) ? 0 : r; }
    double area() { return Math.PI * r * r; }
    double perimeter() { return 2 * Math.PI * r; }
  }
  static class Rectangle extends Shape {
    double w, h; Rectangle(double w, double h) { this.w = Math.max(0, w); this.h = Math.max(0, h); }
    double area() { return w * h; }
    double perimeter() { return 2 * (w + h); }
  }
  public static void main(String[] args) {
    Shape[] list = { new Circle(2.0), new Rectangle(3.0, 4.0), new Circle(1.0) };
    for (int i = 0; i < list.length; i = i + 1) {
      Shape s = list[i];
      System.out.println(s.label() + " -> " + s.info());
    }
  }
}

Sorting by area (idea)

Sıralama fikri:

  • Karşılaştırma: iki şeklin area() değerini kıyasla.
  • Küçük veri için basit bubble/selection sıralaması yeterlidir.
  • Yalnızca Shape metodlarını kullan; tür kontrolü yok.

Code: sort by area

Basit sıralama: sadece area() çağrısı gerektirir. Tür kontrolü yok; bu da polimorfizmin gücüdür.

public class Main {
  static abstract class Shape { abstract double area(); abstract double perimeter(); String label(){ return getClass().getSimpleName(); } }
  static class Circle extends Shape { double r; Circle(double r){ this.r = Math.max(0, r);} double area(){return Math.PI*r*r;} double perimeter(){return 2*Math.PI*r;} }
  static class Rectangle extends Shape { double w,h; Rectangle(double w,double h){ this.w=Math.max(0,w); this.h=Math.max(0,h);} double area(){return w*h;} double perimeter(){return 2*(w+h);} }

  // Very small bubble sort for beginners (ascending by area)
  static void sortByArea(Shape[] arr){
    for(int pass=0; pass<arr.length-1; pass=pass+1){
      for(int i=0; i<arr.length-1; i=i+1){
        if(arr[i].area() > arr[i+1].area()){
          Shape tmp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = tmp;
        }
      }
    }
  }

  public static void main(String[] args) {
    Shape[] a = { new Rectangle(3,4), new Circle(2), new Circle(1) };
    sortByArea(a);
    for(int i=0;i<a.length;i=i+1){
      System.out.println(a[i].label() + " area=" + String.format("%.2f", a[i].area()));
    }
  }
}

Code: total area

Toplam alma: tek döngüde area() çağrıları toplanır. Her eleman kendi hesaplamasını yapar; kodumuz basit kalır.

public class Main {
  static abstract class Shape { abstract double area(); abstract double perimeter(); }
  static class Circle extends Shape { double r; Circle(double r){ this.r=Math.max(0,r);} double area(){return Math.PI*r*r;} double perimeter(){return 2*Math.PI*r;} }
  static class Rectangle extends Shape { double w,h; Rectangle(double w,double h){ this.w=Math.max(0,w); this.h=Math.max(0,h);} double area(){return w*h;} double perimeter(){return 2*(w+h);} }

  static double totalArea(Shape[] arr){
    double sum = 0.0;
    for(int i=0;i<arr.length;i=i+1){
      sum = sum + arr[i].area(); // polymorphic call
    }
    return sum;
  }

  public static void main(String[] args) {
    Shape[] list = { new Circle(1), new Rectangle(2,3), new Circle(0.5) };
    System.out.println("Total area = " + String.format("%.2f", totalArea(list)));
  }
}

Polymorphism style check

Quick check: Which code style best uses polymorphism here?

Recap

Recap: Aynı API ile yazdık, her şekil kendi sonucunu üretti. Yazdırma, sıralama ve toplam gibi işlemler, tek tip kodla çalıştı.

Frequently asked questions

Is the “Polymorphic Behaviors” lesson free?

Yes — the full text of “Polymorphic Behaviors” is free to read here on the web, and the Java Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Polymorphic Behaviors”?

Use polymorphism to print, sort, and aggregate mixed shapes. Keep algorithms tiny and easy to read for mobile. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Polymorphic Behaviors” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Design
  2. Implementation
  3. Polymorphic Behaviors
← Back to Java Academy