Java program on inheritance

INHERITANCE:

The process by which one class acquires the properties(data members) and functionalities(methods) of another class is called inheritance. The aim of inheritance is to provide the re-usability of code so that a class has to write only the unique features and rest of the common properties and functionalities can be extended from the another class

PROGRAM:

//Parent Class Plane
class Plane {
    protected int speed;
    protected String type;

    Plane(String type, int speed) {
        this.type = type;
        this.speed = speed;
    }

    protected void fly() {
        System.out.println(type + " Plane is flying with speed " + speed);
    }

    protected void land() {
        System.out.println(type + " Plane is landing");
    }
}

// Child Class Cargo Plane
class Cargo extends Plane {
    Cargo(int speed) {
        super("Cargo", speed);
    }

    void carryGoods() {
        System.out.println(type + " Plane is carrying goods");
    }
}

// Child Class Passenger Plane
class Passenger extends Plane {
    Passenger(int speed) {
        super("Passenger", speed);
    }

    void carryPassengers() {
        System.out.println(type + " Plane is carrying Passengers");
    }
}

// Child Class Fighter Plane
class Fighter extends Plane {
    Fighter(int speed) {
        super("Fighter", speed);
    }

    void carryWeapons() {
        System.out.println(type + " Plane is carrying weapons");
    }
}

// Main Class
public class PlaneProgram {
    public static void main(String[] args) {
        Cargo c = new Cargo(900);
        Passenger p = new Passenger(800);
        Fighter f = new Fighter(1000);

        c.fly();
        c.carryGoods();
        c.land();

        p.fly();
        p.carryPassengers();
        p.land();

        f.fly();
        f.carryWeapons();
        f.land();
    }

}

OUTPUT:

Cargo Plane is flying with speed 900
Cargo Plane is carrying goods
Cargo Plane is landing
Passenger Plane is flying with speed 800
Passenger Plane is carrying Passengers
Passenger Plane is landing
Fighter Plane is flying with speed 1000
Fighter Plane is carrying weapons
Fighter Plane is landing

Popular Posts