Abstract Class

Abstract class are classes whose object can't be created or class which can't be instantiated. Abstract class has to be declared with abstract keyword.



Syntax:


abstract class <class_name> 
{
// definition
}


Abstract Method

Abstract method is the method without definition. Sometimes programmer just want to declare method. Such methods without definition can be created with abstract keyword.



For example let's say in a class Box there are two method print() and draw(). draw() method need to be declared only. For that abstract keyword can be used.


Syntax:


 abstract void draw();
Important ! Note: A class having one or more abstract methos become abstract class. A class having abstract methods need to be declared abstract.

If a class having abstract method and not declared abstract then at compilation error will be there.


Syntax:


class one 
{
abstract void print();
}


Compiler error:

Error one.java:3: error: one is not abstract and does not override abstract method print() in one
class one
^
1 error
>
Important A class with abstract method need to be declared abstract with abstract keyword.

Correct Program :



abstract class one 
{
abstract void print();
}



Abstract class object can't be created then where it should be used?


Answer of above question is inheritance. Any class inherit abstract class then that class has to define all abstract method of parent class. If a sub class of abstract don't define abstract method then sub class also become abstract class.

Program :


abstract class one
{
abstract void print();
}
class two extends one
{
void print()
{
System.out.println("one class method");
}
}
class th
{
public static void main(String ...arg)
{
two obj=new two();

}
}


What if child class won't define abstract method of parent class?


If a child class won't define parent class abstract method then child class also become abstract means it can't be instantiated.

Program :


abstract class one
{
abstract void print();

}
class two extends one
{
}
class th
{
public static void main(String ...arg)
{
two obj=new two();

}
}

Compiler Error :

Error two.java: error: two is not abstract and does not override abstract method print() in one
class two extends one
^
1 error