Abstract Methods

Abstract Methods:

An abstract class can have abstract methods. You declare a method abstract by adding the abstract keyword in front of the method declaration. Here is how that looks:

public abstract class MyAbstractClass {

 

public abstract void abstractMethod();

}

An abstract method has no implementation. It just has a method signature.

If a class has an abstract method, the whole class must be declared abstract. Not all methods have to be abstract, even if the class is abstract. An abstract class can have a mixture of abstract and non-abstract classes.

Subclasses of an abstract class must implement (override) all abstract methods of its abstract superclass. The non-abstract methods of the superclass are just inherited as they are. They can also be overridden, if needed.

Here is an example subclass of MyAbstractClass:

public class MySubClass extends MyAbstractClass {

 

public void abstractMethod() {

System.out.println(“My method implementation”);

}

}

Notice how MySubClass has to implement the abstract method abstractMethod() from its superclass MyAbstractClass.

The only time a subclass of an abstract class is not forced to implement all abstract methods of its superclass, is if the subclass is also an abstract class.

Multiple inheritance is a feature of some object oriented computer programming languages in which a class can inherit characteristics and features from more than one superclass. It is distinct to single inheritance where a class may only inherit from one particular superclass.

Support we have four java class A, B, C, D

We start with simple example

1. Java Simple Inheritance Example

Class A

public class A {

 

public void a(){

System.out.println(“class A”);

}

}

Class B

public class B extends A{

 

public void a(){

System.out.println(“class B”);

}

}

Class C

public class C extends B{

 

public void a(){

System.out.println(“class C”);

}

}

Class D

public class D {

 

public static void main(String[] args) {

A a=new A();

A b=new B();

A c=new C();

 

a.a();

b.a();

c.a();

}

}

Output

class A
class B
class C

Flexibility through abstraction:

Abstraction in Java is achieved using interfaces and abstract class. abstract means something which is not complete or concrete but abstraction itself is a great programming concept and allow you to write code which is more flexible to change.