Sunteți pe pagina 1din 23

Programming in Java

Lecture: Nested Classes

By
Arvind Kumar
Asst. Professor, LPU
Nested Class
• The Java programming language allows us to define a
class within another class. Such a class is called a nested
class.
Example:
class OuterClass
{
...
class NestedClass
{
...
}
}
Types of Nested Classes
• A nested class is a member of its enclosing class.

• Nested classes are divided into two categories:


– static
– non-static

• Nested classes that are declared static are simply


called static nested classes.

• Non-static nested classes are called inner classes.


Why Use Nested Classes?
• Logical grouping of classes—If a class is useful to only one other
class, then it is logical to embed it in that class and keep the two
together.

• Increased encapsulation—Consider two top-level classes, A and B,


where B needs access to members of A that would otherwise be
declared private. By hiding class B within class A, A's members can
be declared private and B can access them. In addition, B itself can
be hidden from the outside world.

• More readable, maintainable code—Nesting small classes within


top-level classes places the code closer to where it is used.
Static Nested Classes
• A static nested class is associated with its outer class similar to class
methods and variables.

• A static nested class cannot refer directly to instance variables or


methods defined in its enclosing class.

• It can use them only through an object reference.

• Static nested classes are accessed using the enclosing class name:
OuterClass.StaticNestedClass

• For example, to create an object for the static nested class, use this
syntax:
OuterClass.StaticNestedClass nestedObject =
new OuterClass.StaticNestedClass();
Inner Classes
• An inner class is associated with an instance of its enclosing class
and has direct access to that object's methods and fields.

• Because an inner class is associated with an instance, it cannot


define any static members itself.

• 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, we must first instantiate the outer class.


Then, create the inner object within the outer object.
• Syntax:
OuterClass.InnerClass innerObject =
outerObject.new InnerClass();

• Additionally, there are two special kinds of inner classes:


– local classes and
– anonymous classes (also called anonymous inner classes).
Local Classes

• Local classes are classes that are defined in a block, which is a


group of zero or more statements between balanced braces.

• For example, we can define a local class in a method body, a for


loop, or an if clause.

• A local class has access to the members of its enclosing class.

• A local class has access to instance variables. However, a local class


can only access local variables that are effectivelyfinal.
Let’s Do It
• WAP to create a class Demo containing two overloaded
methods demo(). Define a local class X containing show() in
one of the demo() method. Access the show() from the other
demo().
Anonymous Classes
• Anonymous classes enable us to declare and instantiate a class
at the same time.

• They are like local classes except that they do not have a
name.

• The anonymous class expression consists of the following:


1. The new operator
2. The name of an interface to implement or a class to extend.
3. Parentheses that contain the arguments to a constructor, just like a
normal class instance creation expression.
4. A body, which is a class declaration body. In the body, method
declarations are allowed.
 Anonymous classes have the same access to local variables of the
enclosing scope as local classes:
• An anonymous class has access to the members of its enclosing class.
• An anonymous class cannot access local variables in its enclosing scope that are
not declared as final.

 Anonymous classes also have the same restrictions as local classes with
respect to their members:
• We cannot declare static initializers in an anonymous class.

 Note that we can declare the following in anonymous classes:


• Fields
• Extra methods
• Local classes
• we cannot declare constructors in an anonymous class.
Use of Nested Classes
• Local class: Use it if you need to create more than one
instance of a class, access its constructor, or introduce a new,
named type (because, for example, you need to invoke
additional methods later).
• Anonymous class: Use it if you need to declare fields or
additional methods.
• Nested class: Use it if your requirements are similar to those
of a local class, you want to make the type more widely
available, and you don't require access to local variables or
method parameters.
– Use a non-static nested class (or inner class) if you require
access to an enclosing instance's non-public fields and
methods. Use a static nested class if you don't require this
access.
Exercise
• Lovely Professional University have consolidated all academic
department into following four faculties: LFTS, LFBA,
LFAM and LFDE. Each faculty department have some set of
schools as follow:
• Lovely Faculty of Technology and Sciences have following
schools: CSE, ECE, EEE, ME, CE etc.
• Lovely Faculty of Business and Arts have following schools:
HMT, Arts and Language, Law
• Lovely Faculty of Applied Medical Sciences have following
schools: Ayurvedic and Paramedical Science
• Lovely Faculty of Distance Education have following schools:
Distance Education
• Write a test program to simulate LPU organization. Take few
set of employees and student to simulate LPU.
Brain Storming Question
• class OuterTest {
• public static void main(String args[]) {
• Airplane airplane = new Airplane(); //line 5
• Airplane.BlackBox box = airplane.new BlackBox(); // line 6
• box.printVariables();
• } }
• class Airplane {
• String code = "11";
• class BlackBox {
• String code = "22";
• public void printVariables() {
• System.out.print(code);
• System.out.print(Airplane.this.code); // line 20
• } } }
• A) Compile error because of lines 5-6 (incorrect instantiation)
• B) Compile error because of line 20 (can't access Airplane's variables)
• C) 2222
• D) 1111
• E) 2211
• Ans-E
Brain Storming Question
• class OuterTest {
• public static void main(String args[]) {
• Airplane.BlackBox box = new Airplane().new BlackBox(); // line 1
• box.printVariables();
• }
• }
• class Airplane {
• String code = "11";
• class BlackBox {
• String code = "22";
• public void printVariables() {
• System.out.print(code);
• System.out.print(Airplane.this.code); // line 20
• } } }
• A) Compile error because of lines 1 (incorrect instantiation)
• B) Compile error because of line 20 (can't access Airplane's variables)
• C) 2222
• D) 1111
• E) 2211
• Ans-E
Brain Storming Question

• class OuterTest {
• public static void main(String args[]) {
• // instantiation 1
• Airplane airplane = new Airplane();
• Airplane.BlackBox box1 = airplane.new BlackBox();
• // instantiation 2
• Airplane.BlackBox box2 = new Airplane().new BlackBox();
• // instantiation 3
• Airplane airplane3 = new Airplane();
• BlackBox box3 = airplane3.new BlackBox();
• } }
• class Airplane {
• class BlackBox {
• } }
• choose all the correct answers
• A) Instantiation 1
• B) Instantiation 2
• C) Instantiation 3
• Ans- AB
Brain Storming Question
• class AirJet {
• public static void main(String[] args) {
• // instantiation 1
• Engine engine1 = new AirJet().new Engine();
• // instantiation 2
• AirJet.Engine engine2 = new AirJet().new Engine();
• // instantiation 3
• AirJet airjet = new AirJet();
• Engine engine3 = airjet.new Engine();
• // instantiation 4
• Engine engine4 = new Engine();
• }
• class Engine{ }
• }
• Choose all the correct answers
• A) Instantiation 1
• B) Instantiation 2
• C) Instantiation 3
• D) Instantiation 4
• Ans- ABC
Brain Storming Question

• class AirPlane {
• public void fly(int speed) {
• final int e = 1;
• class FlyingEquation {
• {
• System.out.println(e);// line 1
• System.out.println(speed);// line 2
• } } } }
• A) Both statements at lines 1 and 2 are correct
• B) Both statements at lines 1 and 2 are incorrect and cause compilation
errors
• C) Compilation error at line 1 , inner class can't access outer class local
variables
• D) Compilation error at line 2, inner class can't access method's arguments
• Ans-A
Brain Storming Question

• class Body {
• String name = "Body";
• public static void main(String[] args) {
• System.out.println(new Body().new Heart().getPName());
• }
• class Heart {
• String name = "Heart";
• String getPName() {
• // insert statement here
• }
• }
• }
• Choose all the correct answers
• A) return Body.name;
• B) return Body.this.name;
• C) return super.name;
• D) return this.super.name;
• Ans-B
Brain Storming Question

• class Outer
• {
• public static void main(String[] a)
• {
• static class Inner{
• }
• }
• }
• A) compilation error
• B) Runtime error
• C) program will execute successfully
• D) none of these

• Ans-C
Brain Storming Question
• class Outer {
• private int i = 5; // line 1
• Outer(int i ){ // line 2
• this.i = i; // line 3
• System.out.print(++i); // line 4
• }
• class Inner{
• Inner(){
• System.out.print(","+ i++); // line 5
• }
• }
• public static void main(String[] args) {
• int i = 6;
• Outer.Inner in = new Outer(i).new Inner(); // line 6
• }
• }
• choose only one answer:
• A) 6,6
• B) 7,7
• C) 7,6
• D) Compilation error
• Ans-C
Brain Storming Question
• class Test {
• public static void main(String[] args) {
• new OuterClass(); // line 3
• }}
• class OuterClass {
• private int x = 9; // line 5
• public OuterClass() {
• InnerClass inner = new InnerClass(); // line 7
• inner.innerMethod();
• }
• class InnerClass {
• public void innerMethod() {
• System.out.println(x);
• } } }
• choose only one answer:
• (1) Prints 9
• (2) Error during compilation at line 3
• (3) Error during compilation at line 5
• (4) Error during compilation at line 7
• Ans-(1)
Questions

S-ar putea să vă placă și