LAB (8)
LAB (8)
LAB (8)
NESTED CLASSES
Lab-08
Lab Objectives:
1. Understanding the concept of garbage collection
2. Understanding and implementing Nested and Inner classes
3. Understanding and Implementing Encapsulation
Software Required:
JDK & Notepad/ Textpad
Sometimes an object will need to perform some action when it is destroyed. For example, if an
object is holding some non-Java resource such as a file handle or character font, then you might
want to make sure these resources are freed before an object is destroyed. To handle such
situations, Java provides a mechanism called finalization. By using finalization, you can define
specific actions that will occur when an object is just about to be reclaimed by the garbage
collector.
class A {
int i = 50;
@Overrideprotected void finalize() throws Throwable {
System.out.println("From Finalize Method"); }
}
//abandoned
System.gc();System.out.println("done");
final Keyword: The final keyword can be applied with the variables, a final variable that has
no value it is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only.
TASK 2: Value of final variable cannot be changed once declared. Run the
following code and check output.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[])
{
Bike9obj=new Bike9(); obj.run();
}
}//end of class
TASK 3: Try to initialize value of final variable in a constructorTASK 4: Do
not initialize final variable on declaration and try to initialize it anywhere
other than constructor.
TASK 4: Declare final variable as static and try to initialize its value in a
method. Then create a static block and initialize the static final variable value.
Nested and Inner Classes
TASK 5: Run the following code and try to understand its working
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
} }
TASK 6: Declare a local variable in inner class and try to display it in outer
class.
TASK 7: Declare a private variable in outer class and try to display it in inner
class.
TASK 8: Try to declare inner class within a method of outer class.
} }
} }
QUESTIONS
Please Fill the blank space with respective answers to following questions:
ANS: Yes, a final variable can be initialized somewhere other than the constructor, but it
must be initialized exactly once. This could be done in an instance initializer block, a static
initializer block, or directly at the point of declaration.