Nestedclass 150428011452 Conversion Gate01
Nestedclass 150428011452 Conversion Gate01
Example
class OuterClass { ... class NestedClass
{ ... } }
Nested classes are divided into two
categories: static and non-static.
Nested classes that are declared
static are called static nested
classes.
Non-static nested classes are called
inner classes.
Inner Classes
As with instance methods and
variables, an inner class is associated
with an instance of its enclosing class
and has direct access to that object's
methods and fields.
Also, because an inner class is
associated with an instance, it
cannot define any static members
itself.
Example
Objects that are instances of an inner class exist within an instance of
the outer class.
Consider the following classes:
class OuterClass { ... class InnerClass { ... } }
An instance of InnerClass can exist only within an instance of
OuterClass and has direct access to the methods and fields of its
enclosing instance.
To instantiate an inner class, you must first instantiate the outer class.
Then, create the inner object within the outer object with this syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
There are two special kinds of inner classes: local classes and
anonymous classes.
Local Classes
Declaring Local Classes
public class LocalClassExample {
static String regularExpression = "[^0-9]";
public static void validatePhoneNumber(
String phoneNumber1, String phoneNumber2) {
final int numberLength = 10;
class PhoneNumber {
String formattedPhoneNumber = null;
PhoneNumber(String phoneNumber){
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
Anonymous Classes
Anonymous classes enable you to
make your code more concise.
They enable you to declare and
instantiate a class at the same time.
They are like local classes except
that they do not have a name.
Use them if you need to use a local
class only once.
Shadowing