Java Tutorial
Java Tutorial
1 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
Search
In this lesson, you will learn how inner classes are used in Java.
Java Introduction
(JavaIntroduction.cfm)
1. Conventions in These
Notes
2. The Java
Environment Overview
3. Writing a Java
Program
Inner classes, also known as nested classes are classes defined within another
class.
They may be defined as public, protected, private, or with package access.
They may only be used "in the context" of the containingclass (outer class, or
enclosing class), unless they are marked as static.
The outer class can freely instantiate inner class objects within its code; they are
7/23/2013 9:58 PM
Java Tutorial
2 of 16
automatically associated with the outer class instance that created them.
Code in some other class can instantiate an inner class object associated with a
specific instance of the outer class if the inner class definition is public (and its
containing class is public as well).
If the inner class is static, then it can be instantiated without an outer class
instance, otherwise, the inner class object must be attached to an instance of the
outer class.
http://www.learn-java-tutorial.com/InnerClasses.cfm
7. Useful Stuff
Necessary to Go
Further
8. Using the Java
Documentation
Java Basics
(JavaBasics.cfm)
Create a type of object that is only needed within one class, usually for some
short-term purpose.
2. Variables
Create a utility type of object that cannot be used elsewhere (which would allow
the programmer to change it without fear of repercussions in other classes).
Create one-of-a-kind interface implementations (such as individualized event
handlers).
Allow a sort of multiple inheritance, since the inner class may extend a different
class than the outer class extends, and an inner class instance would have
access to its private elements as well as the private elements of the outer class
object it is attached to
Implement one-to-many relationships where the classes are tightly coupled
(meaning that code for one or both of the classes needs access to many of the
private elements of the other class) - the outer class would be the "one" side of
the relationship, with the inner class being the "many" side.
Provide a specialized form of callback, with which a class may pass very limited
access to some of its internal components. Note that:
The collections classes provide an iterator, a class that implements the Iterator
interface to loop through the elements in the collection using hasNext and next
methods.
3. Data
4. Constants and the
final Keyword
5. Mathematics in Java
6. Creating and Using
Methods
7. Variable Scope
Java Objects
(JavaObjects.cfm)
1. Objects
2. Object-oriented
Languages
3. Object-oriented
Programs
4. Encapsulation
Given that the internal structure of the collection may be complex, implementing
the iterator as an inner class enables it to navigate the structure, while not
exposing any other aspects of the collection to the outside world.
5. References
Inner class code has free access to all elements of the outer class object that
contains it, by name (no matter what the access level of the elements is).
7. More on Access
Terms
Outer class code has free access to all elements in any of its inner classes, no
matter what their access term.
8. Adding Data
Members to a Class
An inner class compiles to its own class file, separate from that of the outer class
(the name of the file will be OuterClassName$InnerClassName.class, although
within your code the name of the class will be
OuterClassName.InnerClassName); you cannot use the dollar sign version of the
name in your code.
9. Standard Practices
for Fields and
Methods
An inner class occupies its own memory block, separate from the outer class
memory block.
An inner class may extend one class, which might be unrelated to the class the
outer class extends.
6. Defining a Class
7/23/2013 9:58 PM
Java Tutorial
3 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
1
2
3
4
5
[modifiers]classOuterClassName{
code
[modifiers]classInnerClassName[extendsBaseClassToIn
fieldsandmethods
}
The definition of the inner class is always available for the outer class to use.
Note that:
No inner class objects are automatically instantiated with an outer class object.
Outer class code may instantiate any number of inner class objects - none, one,
or many.
Java-InnerClasses/Demos/MyOuter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
publicclassMyOuter{
privateintx;
MyOuter(intx,inty){
this.x=x;
newMyInner(y).privateDisplay();
}
publicclassMyInner{
privateinty;
MyInner(inty){
this.y=y;
}
privatevoidprivateDisplay(){
System.out.println("privateDisplayx="+x+"and
}
publicvoidpublicDisplay(){
System.out.println("publicDisplayx="+x+"and
}
}
}
7/23/2013 9:58 PM
Java Tutorial
4 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
The MyOuter constructor accepts two parameters; the first is used to populate x.
It creates one MyInner object, whose y property is populated with the second
parameter.
9. Comparing a Number
of Mutually Exclusive
options - The switch
Statement
Note that the inner class has free access to the private outer class x element.
The outer class has free access to the private inner class privateDisplay()
method.
11. Conditional
Expression
The following diagram maps out the memory used by the example.
10. Multidimensional
Arrays in Memory
11. Example - Printing a
Picture
12. Typecasting with
Arrays of Primitives
Inheritance
(Inheritance.cfm)
1. Inheritance
2. Inheritance Examples
7/23/2013 9:58 PM
Java Tutorial
5 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
3. Payroll with
Inheritance
4. Derived Class
Objects
5. Polymorphism
6. Creating a Derived
Class
An inner class instance may be directly instantiated from code in the enclosing
class, without any special syntax:
1
2
3
4
5
6
7
8
9
[modifiers]classOuterClassName{
code
[modifiers]classInnerClassName{
code
}
publicvoidsomeMethod(){
InnerClassNamevariable=newInnerClassName();
}
}
Java-InnerClasses/Demos/Inner1.java
1
2
3
4
5
publicclassInner1{
publicstaticvoidmain(String[]args){
newMyOuter(1,2);
}
}
7/23/2013 9:58 PM
Java Tutorial
6 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
1. Interfaces
2. Creating an Interface
Definition
3. Implementing
Interfaces
If the access term for the inner class definition is public (or the element is
accessible at package access or protected level to the other class), then other
classes can hold references to one or more of these inner class objects
If the inner class is static, then it can exist without an outer class object,
otherwise any inner class object must belong to an outer class instance.
For code that is not in the outer class, a reference to a static or non-static inner
class object must use the outer class name, a dot, then the inner class name:
1
OuterClassName.InnerClassNameinnerClassVariable
If the inner class has an accessible constructor, you can you instantiate one from
outside of the enclosing class, although the syntax is ugly, and there is rarely a
need for this capability.
4. Reference Variables
and Interfaces
5. Interfaces and
Inheritance
6. Some Uses for
Interfaces
7. Annotations
8. Annotation Details
9. Using Annotations
Exceptions
(Exceptions.cfm)
1. Exceptions
2. Handling Exceptions
3. Exception Objects
4. Attempting Risky
Code - try and catch
5. Guaranteeing
Execution of Code The finally Block
6. Letting an Exception
be Thrown to the
Method Caller
7. Throwing an
Exception
8. Exceptions and
Inheritance
9. Creating and Using
Your Own Exception
Classes
If inner class code needs a reference to the outer class instance that it is
attached to, use the name of the outer class, a dot, and this. Remember that if
there is no name conflict, there is no need for any special syntax.
10. Rethrowing
Exceptions
MyOuter.this
12. Assertions
Collections
(Collections.cfm)
7/23/2013 9:58 PM
Java Tutorial
7 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
1. Collections
static members of the outer class are visible to the inner class, no matter what
their access level.
Non-static members of the outer class are not available, since there is not
instance of the outer class to retrieve them from.
4. Creating Collectible
Classes
5. Collections in Java
5.0: Generics
6. Bounded Types
To create a static inner class object from outside the enclosing class, you must
still reference the outer class name
1
newOuterClassName.InnerClassName(arguments)
An inner class may not have static members unless the inner class is itself
marked as static.
7. Extending Generic
Classes and
Implementing Generic
Interfaces
8. Generic Methods
9. Variations on
Generics - Wildcards
Java-InnerClasses/Demos/StaticInnerTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
classStaticOuter{
publicStaticInnercreateInner(){
returnnewStaticInner();
}
staticclassStaticInner{
publicvoiddisplay(){
System.out.println("StaticOuter.Innerdisplaymethod
}
}
}
classStaticInnerTest{
publicstaticvoidmain(String[]args){
newStaticOuter.StaticInner().display();
StaticOuterso=newStaticOuter();
//so.newStaticInner().display();
so.createInner().display();
}
}
Inner Classes
(InnerClasses.cfm)
1. Inner Classes, aka
Nested Classes
2. Inner Class Syntax
3. Instantiating an Inner
Class Instance from
within the Enclosing
Class
4. Inner Classes
Referenced from
Outside the Enclosing
Class
5. Referencing the
Outer Class Instance
from the Inner Class
Code
6. Better Practices for
Working with Inner
Classes
7. Enums
7/23/2013 9:58 PM
Java Tutorial
8 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
Note the commented out line; you cannot create a static inner class instance
attached to an instance of its enclosing class.
Advanced Google
AdWords Training Tutorial
Advanced Google
Analytics Tutorial
Advanced JavaScript
Programming Tutorial
Advanced Microsoft Excel
2010 Training Tutorial
Advanced Microsoft Word
2010 Training Tutorial
Ajax Training Tutorial
Business Writing Training
Tutorial
It is easiest if inner class objects can always be instantiated from the enclosing
class object. You can create a factory method to accomplish this.
Java-InnerClasses/Demos/FactoryInnerOuter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
classFactoryOuter{
FactoryInner[]fi=newFactoryInner[3];
protectedintlastIndex=0;
privateintx=0;
publicFactoryOuter(intx){
this.x=x;
}
publicintgetX(){
returnx;
}
publicvoidaddInner(inty){
if(lastIndex<fi.length){
fi[lastIndex++]=newFactoryInner(y);
}
elsethrownewRuntimeException("FactoryInnerarrayfu
}
publicvoidlist(){
for(inti=0;i<fi.length;i++){
System.out.print("Icanseeintotheinnerclasswhe
fi[i].y+"orcalldisplay:");
fi[i].display();
}
}
publicclassFactoryInner{
privateinty;
protectedFactoryInner(inty){
this.y=y;
}
publicvoiddisplay(){
7/23/2013 9:58 PM
Java Tutorial
9 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
30
31
32
33
34
35
36
37
38
39
40
41
42
43
System.out.println("FactoryInnerx="+x+"and
}
}
}
publicclassFactoryInnerOuter{
publicstaticvoidmain(String[]args){
FactoryOuterfo=newFactoryOuter(1);
fo.addInner(101);
fo.addInner(102);
fo.addInner(103);
fo.list();
//fo.addInner(104);
}
}
For convenience, this file contains both the main class and the FactoryOuter
class (with package access). Note that:
An instance of FactoryOuter contains a three element array of FactoryInner
objects.
The addInner method instantiates a FactoryInner object and adds it to the array
(note that is still automatically associated with the FactoryOuter instance by the
JVM, but we need our own mechanism for keeping track of the inner class
instances we create).
A better approach would be to use one of the collections classes instead of an
array, to avoid running out of room in the array
This is exactly the sort of thing that happens when you obtain an iterator from a
collection class. In order to successfully navigate what is most likely a complex
internal structure, the object will need access to the private elements. So, an
inner class is used, but all you need to know about the object is that it
implements the Iterator interface.
Introduction to Google
Analytics Training Tutorial
Introduction to HTML
Training Tutorial
Introduction to Java
Training Tutorial
Introduction to JavaScript
Training Tutorial
Introduction to Microsoft
Excel 2010 Training
Tutorial
Introduction to Microsoft
Word 2010 Training
Tutorial
Introduction to PHP
Training Tutorial
Introduction to PowerPoint
2010 Training Tutorial
Introduction to SQL
Training Tutorial
Introduction to XML
Training Tutorial
jQuery Fundamentals
Training Tutorial
Java-InnerClasses/Demos/PayrollInnerClass/employees/Employee.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
packageemployees;
importfinance.TransactionException;
publicclassEmployee{
CODEOMITTED
privatedoubleytdPay;
privatePayment[]payments=newPayment[12];
privateintpaymentCount=0;
CODEOMITTED
publicdoublegetYtdPay(){returnytdPay;}
publicPaymentcreatePayment(){
Paymentp=newPayment(payRate);
payments[paymentCount++]=p;
returnp;
}
publicvoidprintPaymentHistory(){
for(Paymentp:payments){
System.out.println(p);
}
}
publicclassPayment{
7/23/2013 9:58 PM
Java Tutorial
10 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
privatedoubleamount;
privatebooleanposted;
publicPayment(doubleamount){
this.amount=amount;
}
publicbooleanprocess()throwsTransactionException{
if(!posted){
ytdPay+=amount;
posted=true;
System.out.println(getFullName()+"paid"+amou
returntrue;
}else{
thrownewTransactionException("Transactionalread
}
}
publicStringtoString(){
returngetFullName()+"paymentof"+amount;
}
}
}
People Tutorial
Note that we have also separated the concepts of creating a payment from
actually posting it. This gives us better control over transactions - note that a
payment cannot be processed twice.
Java-InnerClasses/Demos/PayrollInnerClass/Payroll.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
importemployees.*;
importfinance.*;
publicclassPayroll{
publicstaticvoidmain(String[]args){
Employee.setNextId(22);
Employeee=newEmployee("John","Doe",6000.0);
//looptopayeachmonth
for(intmonth=0;month<12;month++){
Employee.Paymentp=e.createPayment();
try{
p.process();
//HRerrorcausesattempttoprocessJunepaychec
if(month==5)p.process();
}
CSS Training
Flash Training
Marketing Training
Google Training
Social Media Training
Google AdWords Training
Google Analytics Training
JavaScript Training
Microsoft Office Training
7/23/2013 9:58 PM
Java Tutorial
11 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
19
20
21
22
23
24
25
26
27
28
29
30
catch(TransactionExceptionte){
System.out.println(te.getMessage());
}
System.out.println("Ytdpay:"+e.getYtdPay());
}
System.out.println("EmployeePaymentHistory:");
e.printPaymentHistory();
}
We have only one employee for simplicity. As we loop for each month, a
payment is created for each. We try to process the June payment twice
(remember that the array is zero-based, so January is month 0; this matches the
behavior of the java.util.Date class) . The second attempt to process the
payment should throw an exception which our catch block handles.
We retrieve and print the year-to-date pay each time we process a payment.
At the end, we have the Employee object print the entire payment history created
by our calls to the inner class' process method..
Java-InnerClasses/Demos/PayrollInnerClassInterface/employees/Employee.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
packageemployees;
importfinance.*;
publicclassEmployee{
CODEOMITTED
publicclassPaymentimplementsPayable{
privatedoubleamount;
privatebooleanposted;
publicPayment(doubleamount){
this.amount=amount;
}
publicbooleanprocess()throwsTransactionException{
if(!posted){
ytdPay+=amount;
posted=true;
System.out.println(getFullName()+"paid"+amou
returntrue;
}else{
thrownewTransactionException("Transactionalread
}
}
publicStringtoString(){
returngetFullName()+"paymentof"+amount;
}
}
}
Microsoft PowerPoint
Training
SQL Training
XML Training
jQuery Training
Microsoft Outlook Training
SharePoint Training
This code goes one step further to create a Payment inner class that implements
the Payable interface.
7/23/2013 9:58 PM
Java Tutorial
12 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
Java-InnerClasses/Demos/PayrollInnerClassInterface/Payroll.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
importemployees.*;
importfinance.*;
publicclassPayroll{
publicstaticvoidmain(String[]args){
Employee.setNextId(22);
Employeee=newEmployee("John","Doe",6000.0);
//looptopayeachmonth
for(intmonth=0;month<12;month++){
Payablep=e.createPayment();
try{
p.process();
//HRerrorcausesattempttoprocessJunepaychec
if(month==5)p.process();
}
catch(TransactionExceptionte){
System.out.println(te.getMessage());
}
System.out.println("Ytdpay:"+e.getYtdPay());
}
System.out.println("EmployeePaymentHistory:");
e.printPaymentHistory();
}
The only difference here is that we declare the variable holding the payments as
Payable, hiding the fact that it is an inner class.
In Java 5, the enum element was introduced. Long sought by the C/C++ part of
the Java community, enums provide a set of predefined constants for indicating a
small set of mutually exclusive values or states.
7/23/2013 9:58 PM
Java Tutorial
13 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
The other approaches all have some sort of flaw, particularly as involves
type-safety.
Interfaces defining only constants were commonly used, and several are
grandfathered into the API, like SwingConstants. But, there is a minor problem
that if you implement an interface in order to gain the constants, you then have
additional public elements in that class that you wouldn't really want to provide to
the outside world.
1
2
3
4
publicclassMyFrameextendsJFrameimplementsSwingConstan
MyFrameframe=newMyFrame();
//frame.HORIZONTALisnowpubliclyavailable
While not terrible, there isn't any real meaning to frame.HORIZONTAL, or any
reason we would want to make it available to the outside world.
Using plain old integers seems straightforward enough, but, if you perhaps have
a method that requires one of that set of values to be passed in, the parameter
would be typed as int. A caller could supply any int value, including ones you
wouldn't expect.
1
2
3
4
5
6
7
8
privateintLEFT=0;
privateintRIGHT=1;
privateintCENTER=2;
publicvoidsetAlignment(intalign){...}
//compilerwouldallow:
setAlignment(99);
Java enums provide a type-safe way of creating a set of constants, since they
are defined as a class, and therefore are a type of data.
A disadvantage to this approach is that the set of values is written into the code.
For sets of values that may change, this would require recompiling the code, and
would invalidate any serialized instances of the enum class. For example, if we
offered a choice of benefits plans to our employees, the set of available plans
would not be a good candidate for an enum, since it is likely that the set of
available plans would eventually change.
7/23/2013 9:58 PM
Java Tutorial
14 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
indexes starting at 0, in the order that the names were defined - there is no way
to change this, but there is a route to get specific values which have a complex
internal state.
1
2
3
publicenumEnumName{
value1,value2,value3,...;
}
publicenumAlignment{left,right,center;}
Java-InnerClasses/Demos/BookWithEnum.java
1
2
3
4
5
publicclassBookWithEnum{
privateintitemCode;
privateStringtitle;
privatedoubleprice;
privateCategorycategory;
7/23/2013 9:58 PM
Java Tutorial
15 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
publicenumCategory{required,supplemental,optional,
publicBookWithEnum(
intitemCode,Stringtitle,
doubleprice,Categorycategory){
setItemCode(itemCode);
setTitle(title);
setPrice(price);
setCategory(category);
}
publicBookWithEnum(Stringtitle){
setItemCode(0);
setTitle(title);
setPrice(0.0);
setCategory(Category.unknown);
}
publicintgetItemCode(){
returnitemCode;
}
publicvoidsetItemCode(intitemCode){
if(itemCode>0)this.itemCode=itemCode;
}
publicStringgetTitle(){
returntitle;
}
publicvoidsetTitle(Stringtitle){
this.title=title;
}
publicvoidsetPrice(doubleprice){
this.price=price;
}
publicdoublegetPrice(){
returnprice;
}
publicvoidsetCategory(Categorycategory){
this.category=category;
}
publicvoidsetCategory(StringcategoryName){
this.category=Category.valueOf(categoryName);
}
publicCategorygetCategory(){
returncategory;
}
publicvoiddisplay(){
System.out.println(itemCode+""+title+":"+cat
",Price:$"+price);
}
}
7/23/2013 9:58 PM
Java Tutorial
16 of 16
http://www.learn-java-tutorial.com/InnerClasses.cfm
Enums are more than just a set of integer constants. They are actually a set of
unique object instances, and, as objects, can have multiple fields. So, an enum is
a class with a fixed number of possible instances, each with it's own unique
state, and each of the possible instances is created automatically and stored as
static field under the same name. (In design pattern terms, an enum is a
Flyweight - a class where only a limited number of fixed states exist.)
To create a more complex enum class:
1. Declare as before.
2. Declare any additional fields and accessor methods as with a regular class.
While you can actually write mutator methods to create what is called a
mutable enum, this practice is strongly discouraged.
3. Write one constructor.
4. Within the curly braces, again supply a comma-separated list of names,
which will be the individual values, but this time with a parameter list. The
enum values will be constructed with the data you provide.
All pages and graphics in this Java Tutorial is copyright 2013 and are the property of Webucator, Inc.
(http://www.webucator.com) unless otherwise specified. The purpose of this website is to help you learn Java on your own
and use of the website implies your agreement to our Terms of Service (tos.cfm).
7/23/2013 9:58 PM