Pages

Abstraction in java (abstract class)

abstraction in java :: futureX

Abstraction is a process of hiding the implementation details and showing only functionality to the user.Abstraction lets you focus on what the object does instead of how it does it.


Ways to achieve Abstraction:
Abstract class (0 to 100%)
Interface (100%)

Abstract class:
A class that is declared as abstract is known as abstract class.It needs to be extended and its method implemented.It cannot be instantiated.


           abstract class class_name{}

Abstract method:
A method that is declared as abstract and does not have implementation is known as abstract method.


          abstract return_type method_name();    //no braces{}

Example:

abstract class Shape{
abstract void draw();
}

class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}

class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}

class Test{
public static void main(String args[]){
Shape s=new Circle();
s.draw();
}
}


Note: An abstract class can have data member,abstract method,method body,constructor and even main() method.

Rule: If there is any abstract method in a class, that class must be abstract.

//Shape is not abstract and does not override abstract method //draw() in shape

class Shape{
abstract void draw();
}


                   JAVA TUTORIALS HOMEPAGE