Java Abstract classes and Abstract Methods with Examples

Java Abstract classes and Abstract Methods with Examples

Abstract Class

The class which is declared with abstract keyword is known as abstract class.Abstract classes are The classes that contain one or more abstract methods.An Abstract Class can never be instantiated.means we are not allowed to create object of an abstract class.An abstract class contain abstract methods and concrete methods and both. if a class contain at least one abstract method you need to declare the class as abstract.if a class doesn't contain abstract methods also we can declare class as abstract class.
The structure of abstract class
public abstract class ClassName{
//abstract methods;
//concrete methods;

}

public abstract class Hello {//abstract class declaration
//concrete method ,method has implementation
public void welcome(){
System.out.println("hello world");
}
//abstract method declaration
public abstract void show();


}

Abstract classes are partially incomplete classes.
As we discussed An Abstract class Can never be instantiated.Let's See if we create instance to An abstract class what will happen.
What If Try to create instance to An abstract class?
package com.java2study.practice;
public abstract class Test {
//cocrete method
public void welcome(){
System.out.println("hello world");
}
//abstract method
public abstract void show();

public static void main(String[] args) {
Test test = new Test();
test.welcome();

}

}


output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Cannot instantiate the type Test

at com.java2study.practice.Test.main(Test.java:12)
From the above observation we can conclude that an abstract class can never be instantiated.

Abstract Method

An abstract method which has been declared with abstract keyword but not implemented.which means abstract methods contain no body.so abstract method should ends with semicolon(;).abstract methods doesn't have curly bases to define method functionality.for abstract methods you need to write implementation code in subclasses.
The structure of abstract method
public abstract void print();
In java abstract method must be declared with abstract keyword. otherwise We will get compile time error.
Example To Abstract class and abstract method
package com.java2study;

public abstract
class Hello {
public abstract void print();
public void show(){
System.out.println("Hello");
}

}

public class AbstractTest extends Hello {

@Override
void print() {
System.out.println("hello iam Java");

}


public static void main(String[] args) {
AbstractTest t = new AbstractTest();
t.print();
t.show();

}

}


Output
hello iam Java
Hello

-->