From charlesreid1

(Redirected from Java/Abstract Classes)

An abstract tree in Java is a class that is not intended to be implemented itself, but is nonetheless a full-on Java class.

As such, it can declare fields and implement methods.

Basic Abstract Class: Implements Methods

Here, we declare an abstract class called AbstractTree. This takes a generic type <E>, and it does not define any constructors. It does define a few methods, some of which pass along <E> when passing method parameters.

// The abstract tree:
public abstract class AbstractTree<E> {
	int size;
	char parity; // just a made-up doohickeythingamajig

	/** Boolean method definition. */
	public boolean isEmpty() {
		return size()==0;
	}

	/** Int method definition. */
	public int size() { 
		return this.size;
	}

	/** Some kind of access method. */
	public void setParity(char c){ 
		this.parity = c;
	}
}

Now if we take a look at the concrete class, we have a class that implements two additional methods, and calls these two new methods. The ConcreteTree class defines them, but they access fields and methods defined in the parent class, AbstractTree.

Note that the concrete implementation is actually dealing with data, and so has the responsibility of implementing the Empty exception.

// A nice little exception
class Empty extends IllegalStateException {}

// The concrete tree:
public class ConcreteTree<E> extends AbstractTree<E> {

	public ConcreteTree(int n) { 
		this.size = n;
		this.setParity('x');
	}

	/** Print "parity" of this thing (whatever that is). */
	public void printParity() { 
		if(isEmpty()) { 
			throw new Empty();
		}
		System.out.println("Parity: "+this.parity);
	}

	/** Print size of this thing. */
	public void printSize() { 
		if(isEmpty()) { 
			throw new Empty();
		} else {
			System.out.println("Size: "+this.size);
		}
	}

	public static void main(String[] args) { 
		ConcreteTree<String> c = new ConcreteTree<String>(5);
		c.printSize();
		c.printParity();
	}
}

As a result, when we run this class and its driver (at the bottom of the class), we see:

$ javac ConcreteTree.java && java ConcreteTree
Size: 5
Parity: x


Abstract Abstract Class: Implements No Methods

Here is an abstract class implementing no methods, which has some of the methods required by the Trees/ADT (trees abstract data type):

  • element()
  • root()
  • is_root
  • parent
  • num_children
  • is_leaf
public abstract class Tree {
  abstract Node root();
  abstract Node parent(Node n);
  abstract int num_children(Node n);
  abstract Node children(Node n);
  abstract boolean is_leaf(Node n);
  abstract int length();
  abstract boolean isEmpty();
  abstract Iterator<E> iterator();
}


Java API Docs tutorial: link