we have seen that functions are abstractions over expressions and that procedures are abstractions over commands.
The abstraction principle suggests that we can extend this to give us abstractions over declaration.
In Java, this concept appear in the form of abstract class and interface.
An abstract class can only extend one class. But an interface can extend many interfaces. Abstract class is not pure. It maybe contain some abstract methods and some non-abstract methods (i.e. implemented methods). While interface does not contain any implementation code. It is PURE.
[modifier] abstract class A {
[variable declaration;]
[method declaration;]
}
class A [extends B] [implements
interface-names] {
[variable declaration;]
[method declaration;]
}
A Example:
public abstract class MyAbstractClass{
int aVariable;
public abstract int aAbstractMethod();
public void aNormalMethod (){
System.out.println("A normal method);
}
}
public class AConcreteClass extends
MyAbstractClass{
....
public int aAbstractMethod() {
System.out.println("Implement superclass's
abstract method");
}
A concrete Example:
public interface Countable {
int X=20;
int Y=30;
//declaring interface constants
void Counting();
//declaring a interface method
}
class Example implements Countable {
int x=X;
int y=Y;
int sum=0;
public void Counting(){
// implements interface method
sum=x+y;
System.out.println("Sum is "+sum);
}
}
class Example1 extends Example
implements Countable{
int x=X;
int y=Y;
int sub = 0;
public void Counting(){
// implements interface abs method
sub=y-x;
System.out.println("Sub is "+sub);
}
}
public class ResultOfCount {
public static void main(String args[]){
Example X=new Example();
X.Counting();
Example1 Y = new Example1();
Y.Counting();
}
}
The output of the program:
Sum is 50
Sub is 10
Counting() method is implemented (overridden) by two classes that implements
Countable interface.
An interface may have many methods. If a class implements an interface, but
only implements some of its methods, then this class becomes an abstract
class. It cannot be instantiated.
Type parameters
A declaration can make use of previously defined values. Now, a declaration can also make use of previously defined types.
Ada and Java can have type parameters.
Example:
class Vector {
....
final synchronized void addElement(Object obj){
....
}
}
class Item{
....
}
Item element = new Item();
Vecter aVector = new Vector();
aVector.addElement(element);