Introducing Nested And Inner Classes Java Help

Introducing Nested And Inner Classes

It is possible to define a class within another class; such classes are known as nested lasses. The Scope of a nested class is bounded by the scope of its enclosing class. Thus, if class Bis defined within class A, then Bis known to A, but not outside of A. A blindside. class h as access to the members, including private members, of the,class in which it is nested, However, the enclosing class does-not have ~cress to the members of the nested class. There are two types of nested classes: static and lion-static. A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. The most important type of nested class is the inner class. An Daimler class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class-is fully within the scope of its enclosing class. The following program illustrates how to define and use an inner class. The class named Outcry has one instance variable named outer_x, one instance method named test ), and defines one inner class called Inner.

In the program, ln inner class named Inner is defined within the scope of class Outer. Therefore, any code in class Inner can directly access the variable outcr x, An “instance method namcdsdisplayt ) is defined inside Inner, This method displays outer_x on the standard output stream. The amine method of Underclassmen creates an instance of class Outer and invokes its test  method. That method creates an instance of class Inner and methodicalness is called.
It is important to realize that class Inner is known only within the scope of class Outer. The Java compiler generates an error message if any code outside ( f class  Outerattempts to instantiate class Inner. Generalizing, a nested class is no different than any other progrnm element: it is knownonly within its enclosing scope. As explained, an inner class has access to all of the members of its enclosing class, but the reverse is not true. Members of the inner class arc known only within the sc ope of the inner class and may not be used by the outer class: For example

JavaHelpOnline.com

  • Feel free to send us an inquiry, we will reply back in hours.
 

Verification

Posted on September 17, 2014 in A Closer Look at Methods and Classes

Share the Story

About the Author

Back to Top