Hi There!

I'm Dan Schlegel, an Associate Professor in the Computer Science Department at SUNY Oswego

Polymorphism Example

The following code appears in Main.java : 

class Polygon {
    int sides;
    
    public Polygon(int sides){
        this.sides = sides;
    }
    
    protected String getName(){
        return "Polygon";
    }
    
    public void printDescription(){
        System.out.println(getName() + " has " + sides + " sides");
    }
}

class Square extends Polygon {
    int sideLength;
    
    public Square(int sideLength) {
        super(4); 
        this.sideLength = sideLength;
    }

    @Override
    protected String getName(){
        return "Square";
    }

    @Override
    public void printDescription(){
        super.printDescription();
        System.out.println("It has side length: " + sideLength);
    }
}

class Triangle extends Polygon {
    double side1, side2, side3;
    
    public Triangle(double side1, double side2, double side3) {
        super(3); 
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    @Override
    protected String getName(){
        return "Triangle";
    }

    @Override
    public void printDescription(){
        super.printDescription();
        System.out.println("It has side lengths: " + side1 + ", " + side2 + ", " + side3);
    }
}

public class Main {
    public static void main(String[] args) { 
        Polygon poly = new Polygon(5);
        Square square = new Square(10);
        Triangle tri = new Triangle(2.3, 1.7, 3.4);
        poly.printDescription();
        System.out.println();
        square.printDescription();
        System.out.println();
        tri.printDescription();
    }
}

It produces the following output: 

Polygon has 5 sides

Square has 4 sides
It has side length: 10

Triangle has 3 sides
It has side lengths: 2.3, 1.7, 3.4