JetBrains Academy: Hiding and overriding - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: Hiding and overriding

Saying animals:

You have four classes: Animal, Cat, Dog, and Duck. The class animal has a method say(). This method does nothing.

Override the method in all subclasses. Overridden methods should output what these animals say (using System.out.println).

  • Cat: meow-meow
  • Dog: arf-arf
  • Duck: quack-quack
class Animal {

    public void say() {
        System.out.println("...An incomprehensible sound...");
    }
}

class Cat extends Animal {
    public void say() {
        System.out.println("meow-meow");
    }
}

class Dog extends Animal {
    public void say() {
        System.out.println("arf-arf");
    }
}

class Duck extends Animal {
    public void say() {
        System.out.println("quack-quack");
    }
}

Shapes area:

You have five classes: Shape, Triangle, Circle, Square, and Rectangle. The class Shape has a method area(). This method does nothing. Override the method in all subclasses. Overridden methods should return an area of a particular figure. Use class fields for this.

class Shape {

    public double area() {
        return 0;
    }
}

class Triangle extends Shape {
    double height;
    double base;
    @Override
    public double area() {
        return 0.5 * base * height;
    }
}

class Circle extends Shape {
    double radius;
    @Override
    public double area() {
        return Math.PI * Math.pow(radius, 2);
    }
}

class Square extends Shape {
    double side;
    @Override
    public double area() {
        return Math.pow(side, 2);
    }
}

class Rectangle extends Shape {
    double width;
    double height;
    @Override
    public double area() {
        return width * height;
    }
}