Millised on sisemiste klasside tüübid programmeerimiskeeles?
sobes.tech AI
Vastus AI-lt
Java's inner classes:
-
Static Nested Classes: Behave like regular static members of a class. They do not have access to non-static members of the outer class. They are created without an instance of the outer class.
public class Outer { private static String staticMsg = "Static message"; private String instanceMsg = "Instance message"; static class StaticNested { void displayStatic() { // Access to outer class's static members System.out.println(staticMsg); // No access to outer class's non-static members // System.out.println(instanceMsg); // Compilation error } } } -
Inner Classes: Associated with an instance of the outer class. They have full access to all (static and non-static) members of the outer class, including private ones. They can be declared as
private,protected,package-private, orpublic.public class Outer { private static String staticMsg = "Static message"; private String instanceMsg = "Instance message"; class Inner { void display() { // Access to static and non-static members System.out.println(staticMsg); System.out.println(instanceMsg); } } } -
Local Classes: Declared within a block (method, constructor, or static initializer). They are only accessible within that block. They can access
finalor effectivelyfinallocal variables and parameters, as well as all members of the outer class.public class Outer { private String instanceMsg = "Instance message"; void methodWithLocalClass() { final String localVar = "Local variable"; // or effectively final class Local { void display() { System.out.println(instanceMsg); System.out.println(localVar); } } Local localObj = new Local(); localObj.display(); } } -
Anonymous Classes: Classes without a name. Used for declaring and instantiating a class at the same time, which either implements an interface or extends a class. Useful for creating small, one-time objects.
public class Outer { void methodWithAnonymousClass() { // Anonymous class implementing Runnable Runnable myRunnable = new Runnable() { @Override public void run() { System.out.println("Running from anonymous class"); } }; new Thread(myRunnable).start(); // Anonymous class extending Thread Thread myThread = new Thread() { @Override public void run() { System.out.println("Running from anonymous class extending Thread"); } }; myThread.start(); } }
Comparison of inner class types:
| Type | Declaration Location | Access to Outer Class Members | Need Outer Class Instance to Create | Access Modifiers |
|---|---|---|---|---|
| Static Inner Class | Inside class, with static |
Only static | No | All |
| Inner Class | Inside class (non-static) | All (static and non-static) | Yes | All |
| Local Class | Inside a block (method, constructor, initializer) | All outer members + final or effectively final local variables |
Yes | No |