Inner Classes
Python |
Java |
A class might be defined
just for use in another class definition. For example, a LinkedStack class might use a OneWayNode
class. Ideally, the definition
of OneWayNode would be nested within LinkedStack, but that is not allowed. For the sake of comparison, here is
an implementation of these two classes: class
OneWayNode: def __init__(self, data,
next):
self.data = data
self.next = next class
LinkedStack: def __init__(self):
self.items = None
self.size = 0 def push(self, element):
self.items = OneWayNode(element, self.items)
self.size += 1 def pop(self):
element = self.items.data
self.items = self.items.next
self.size -= 1
return element def peek(self):
return self.items.data def isEmpty(self):
return len(self) == 0 def __len__(self):
return self.size |
A class might be defined
just for use in another class definition. For example, a LinkedStack class might use a OneWayNode
class. The definition of OneWayNode can be nested within LinkedStack. OneWayNode is specified as a private class,
sometimes also called an inner class.
Here is an implementation:
public class
LinkedStack<E> implements TrueStack<E>{ private
OneWayNode<E> items; private int size; public LinkedStack(){
this.items = null;
this.size = 0; } public void push(E
element){
this.items = new OneWayNode<E>(element, items); this.size += 1; } public E pop(){ E
element = this.items.data;
this.items = this.items.next;
this.size -= 1;
return element; } public E peek(){
return this.items.data; } public boolean isEmpty(){
return this.size() == 0; } public int size(){
return this.size; } public Iterator<E>
iterator(){
return null;
# Deferred to another }
# topic private class
OneWayNode<E>{
private E data;
private OneWayNode next;
private OneWayNode(E data, OneWayNode next){
this.data = data;
this.next = next; } } } |