Learn abstraction in java

Hey guys!! How are you doing!! Welcome to flower brackets blog. Today we will learn abstraction in java.

Abstraction is defined as showing necessary details and hiding the implementation details to the user.

For example, in an ATM machine when user inserts his card a list of ATM services is displayed namely, banking, mini statement, balance enquiry, quick cash, etc. etc.

User doesn’t know what is running behind, what type of programming, functionality involved and where the server is kept by bank so that the data is collected and processed.

So a user is not aware of all these stuffs. Only functionality offered by banks is shown to the user and hiding implementation details.

We can accomplish abstraction using abstract classes and interface.


Abstract class and abstract methods

  1. We cannot create instance of an abstract class.
  2. If a class consists of at least one abstract method then it should be declared as abstract class.
  3. “abstract” keyword is used to declare an abstract class.
  4. An abstract class consists of non-abstract and abstract methods.
  5. There will be no implementation for an abstract method.
  6. Subclass should redefine method defined in abstract class. Hence overriding definition of all abstract methods.
  7. An abstract class also consists of default and parameterized constructor.

Let’s see java program on abstraction,

abstract class Car  
{
String color;
// abstract methods
abstract void accelerate();
abstract void stop();

// abstract class constructor
public Car(String color)
{
System.out.println("Car constructor called");
this.color = color;
}

// concrete method
public String getColor()
{
return color;
}
}

class HatchBack extends Car 
{
private int doors;
public HatchBack(String color, int doors)
{
// calling Car constructor
super(color);
this.doors = doors;
System.out.println("Hatchback constructor called");
}
   @Override 
void accelerate()
{
System.out.println("Hatchback accelerating");
}

@Override
public String toString()
{
return "Hatchback color is " + super.color " with " + doors + " doors" ;
}

@Override
void stop()
{
System.out.println("Hatchback stopping");
}
}

class Sedan extends Car
{
public Sedan(String color)
{
// calling Car constructor
super(color);
System.out.println("Sedan constructor called");
this.color = color;
}

@Override
public String toString()
{
return "Sedan color is " + super.color;
}

@Override
void accelerate()
{
System.out.println("Sedan accelerating.");
}

@Override
void stop()
{
System.out.println("Sedan stopping");
}
}

public class AbstractDemo 
{
public static void main(String[] args)
{
HatchBack swift = new HatchBack("Green",5);
Sedan dzire = new Sedan("Red");
System.out.println(swift.toString());
System.out.println(dzire.toString());
}
}

Output:

Car constructor called
Hatchback constructor called
Car constructor called
Sedan constructor called
Hatchback color is Green with 5 doors
Sedan color is Red

Related Posts