Data Structures and Algorithms with Object-Oriented Design Patterns in Ruby
next up previous index

Nested Classes

In Ruby it is possible to define one class inside another. A class defined inside another one is called a nested class .

Consider the following Ruby code fragment:

class A < Object

    def initialize
	@y = 0
    end

    class B < Object

	def initialize
	    @x = 0
	end

	def f
	    # ...
	end

    end

end
This fragment defines the class A which contains the nested class B.

A nested class behaves like any ``outer'' (un-nested) class. It may contain methods and instance attributes, and it may be instantiated like this:

obj = A::B.new()
This statement creates an new instance of the nested class B. Given such an instance, we can invoke the f method in the usual way:
obj.f

Note, it is not necessarily the case that an instance of the outer class A exists even when we have created an instance of the inner class. Similarly, instantiating the outer class A does not create any instances of the inner class B.

The methods of a nested class may access the instance attributes of the nested class instance but not of any outer class instance Thus, method f can access the instance attribute @x, but it cannot access the instance attribute @y.


next up previous index

Bruno Copyright © 2004 by Bruno R. Preiss, P.Eng. All rights reserved.