Test

Submitted by: Submitted by

Views: 141

Words: 455

Pages: 2

Category: US History

Date Submitted: 09/19/2013 05:14 AM

Report This Essay

Static class in Java

1) Can a class be static in Java ?

YES, we can have static class, static instance variables as well as static methods and also static block.

Java allows us to define a class within another class. Such a class is called a nested class. The class which enclosed nested class is known as Outer class. In java, we can’t make Top level class static. Only nested classes can be static.

2) What are the differences between static and non-static nested classes?

1) Nested static class doesn’t need reference of Outer class, but Non-static nested class or Inner class requires Outer class reference.

2) A nested static class cannot access non-static members of the Outer class. It can access only static members of Outer class. While Inner class(or non-static nested class) can access both static and non-static members of Outer class.

3) An instance of Inner class cannot be created without an instance of outer class and an Inner class can reference data and methods defined in Outer class in which it nests, so we don’t need to pass reference of an object to the constructor of the Inner class. For this reason Inner classes can make program simple and concise.

/* Java program to demonstrate how to implement static and non-static classes in a java program. */

class OuterClass{

private static String msg = "GeeksForGeeks";

// Static nested class

public static class NestedStaticClass{

// Only static members of Outer class is directly accessible in nested static class

public void printMessage() {

// Try making 'message' a non-static variable, there will be compiler error

System.out.println("Message from nested static class: " + msg);

}

}

// non-static nested class - also called Inner class

public class InnerClass{

// Both static and non-static members of Outer class are accessible in

// this Inner class

public...