Java program on abstraction, birds example

ABSTRACTION:

Abstraction is a process of hiding the implementation details and showing only functionality to the user. 
There are two ways to achieve abstraction in java:
  1. Abstract class (0 to 100%)
  2. Interface (100%)
A class that is declared using “abstract” keyword is known as abstract class. It can have abstract methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-abstract class) cannot have abstract methods.

PROGRAM:

abstract class Bird {
    abstract void fly();

    abstract void eat();
}

abstract class Eagle extends Bird {
    void fly() {
        System.out.println("Eagle flies at high altitude");
    }

    abstract void eat();
}

class Serpentine extends Eagle {
    void eat() {
        System.out.println("Serpentine Eagle eats snakes");
    }
}

class Golden extends Eagle {
    void eat() {
        System.out.println("Golden Eagle eats fishes");
    }
}

class Sparrow extends Bird {
    void fly() {
        System.out.println("Sparrow flies at low altitudes");
    }

    void eat() {
        System.out.println("Sparrow eats grains");
    }
}

class Crow extends Bird {
    void fly() {
        System.out.println("Crow flies at mid altitudes");
    }

    void eat() {
        System.out.println("Crow eats flesh");
    }
}

class Sky {
    void allowBird(Bird ref) {
        ref.fly();
        ref.eat();
    }
}

public class BirdApp {

    public static void main(String args[]) {
        Serpentine se = new Serpentine();
        Golden ge = new Golden();
        Sparrow sp = new Sparrow();
        Crow c = new Crow();
        Sky s = new Sky();
        s.allowBird(se);
        s.allowBird(ge);
        s.allowBird(sp);
        s.allowBird(c);

    }
}

OUTPUT:

Eagle flies at high altitude
Serpentine Eagle eats snakes
Eagle flies at high altitude
Golden Eagle eats fishes
Sparrow flies at low altitudes
Sparrow eats grains
Crow flies at mid altitudes
Crow eats flesh
 

Popular Posts