Assignment #4 (Abstract and Interface ) - Rozeenaa/LearningJava GitHub Wiki
Abstract:
A java abstract class is a class which cannot be instantiated, meaning you cannot create new instance of an abstract class. The purpose of an abstract class is to function as a base for subclasses.
Declaring an Abstract Class in Java
In java you declare that a class is abstract by adding the abstract keyword to the class declaration. Here is a java abstract class example:
public abstract class MyClass {
}
Abstract Methods
An abstract class can have absract methods. You declare a method abstract by adding the abstract keyword in front of the method declaration. Here is a java abstract method example :
public abstract class MyClass {
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 in an abstract class have to be abstract methods. An abstract class can have a mixture of abstract and non-abstract methods.
Interface
An interface is a refrence type in java, it is similar to class, it is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an interface:
Below given is an example of interface:
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}