Java program on abstraction, planes 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:
- Abstract class (0 to 100%)
- 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 Plane {
abstract void takeOff();
abstract void fly();
abstract void land();
}
class Cargo extends Plane {
void takeOff(){
System.out.println("Cargo Plane took off");
}
void fly(){
System.out.println("Cargo Plane is flying");
}
void land(){
System.out.println("Cargo Plane landed");
}
}
class Passenger extends Plane {
void takeOff(){
System.out.println("Passenger Plane took off");
}
void fly(){
System.out.println("Passenger Plane is flying");
}
void land(){
System.out.println("Passenger Plane landed");
}
}
class Fighter extends Plane {
void takeOff(){
System.out.println("Fighter Plane took off");
}
void fly(){
System.out.println("Fighter Plane is flying");
}
void land(){
System.out.println("Fighter Plane landed");
}
}
class Airport {
void allowPlane(Plane p){
p.takeOff();
p.fly();
p.land();
}
}
public class Main{
public static void main(String[] args){
Cargo c=new Cargo();
Passenger p=new Passenger();
Fighter f=new Fighter();
Airport a=new Airport();
a.allowPlane(c);
a.allowPlane(p);
a.allowPlane(f);
}
}
abstract void takeOff();
abstract void fly();
abstract void land();
}
class Cargo extends Plane {
void takeOff(){
System.out.println("Cargo Plane took off");
}
void fly(){
System.out.println("Cargo Plane is flying");
}
void land(){
System.out.println("Cargo Plane landed");
}
}
class Passenger extends Plane {
void takeOff(){
System.out.println("Passenger Plane took off");
}
void fly(){
System.out.println("Passenger Plane is flying");
}
void land(){
System.out.println("Passenger Plane landed");
}
}
class Fighter extends Plane {
void takeOff(){
System.out.println("Fighter Plane took off");
}
void fly(){
System.out.println("Fighter Plane is flying");
}
void land(){
System.out.println("Fighter Plane landed");
}
}
class Airport {
void allowPlane(Plane p){
p.takeOff();
p.fly();
p.land();
}
}
public class Main{
public static void main(String[] args){
Cargo c=new Cargo();
Passenger p=new Passenger();
Fighter f=new Fighter();
Airport a=new Airport();
a.allowPlane(c);
a.allowPlane(p);
a.allowPlane(f);
}
}
OUTPUT:
Cargo Plane took offCargo Plane is flying
Cargo Plane landed
Passenger Plane took off
Passenger Plane is flying
Passenger Plane landed
Fighter Plane took off
Fighter Plane is flying
Fighter Plane landed