From charlesreid1

No edit summary
No edit summary
Line 6: Line 6:


<pre>
<pre>
// The abstract tree:
public abstract class AbstractTree<E> {
public abstract class AbstractTree<E> {
int size;
int size;
Line 32: Line 33:


<pre>
<pre>
// A nice little exception
class Empty extends IllegalStateException {}
class Empty extends IllegalStateException {}


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



Revision as of 17:53, 18 June 2017

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.

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