Saturday, January 11, 2020

Abstract Classes

Abstract Classes

Abstract classes are one of the ways to apply Abstraction in Java. Another way to apply Abstraction in Java is Interfaces. A class can be "abstract" in nature or "concrete".Concrete classes are complete classes and we can create the objects of concrete classes and use them. Abstract classes are incomplete classes and we can not create objects of abstract classes. When one or more than one method of the class is abstract than that class must also be declared as abstract. Any class extending the abstract class either must implement the abstract methods in its superclass or it should be declared as abstract also.

Abstract classes in java
Example Abstract Class


In the diagram above, The class "Shape" is an abstract class(incomplete knowledge of behavior) so we must declare it as an abstract class.

Any class extending the abstract class either must implement the abstract methods in its superclass or it should be declared as abstract also.

Declaring an Abstract Class


Abstract class declaration
Abstract class declaration


An abstract class may have static fields and static methods. You can use these static members with a class reference (for example, AbstractClassName.staticMethodName()) as you would with any other class. An abstract class can not be declared as final.

Example:(Abstract classes)



abstract class A{   //Abstract class having abstract                        //method
    abstract void m1();//Abstract method
    void m2()           // Concrete method
    {
        System.out.println("I am in Super class A");
    }
}
class B extends A{ //Concrete class

    @Override
    void m1() {
        System.out.println("I am in Sub class B");
    }//The type B must implement the inherited
                //abstract method A.m1()
   
}
public class AbastractDemo {

    public static void main(String[] args) {
    //  A a=new A(); not possible, 
    //we can not create 
    //object of Abstract class
        B b=new B();
        b.m2();
        b.m1();
    }

}


Output:

I am in Super class A
I am in Sub class B

Video Tutorial