Junior
What are the types of classes in Java?
sobes.tech AI
Answer from AI
- Regular (concrete) classes: Can be instantiated, contain fields, methods, constructors.
- Abstract classes: Cannot be instantiated directly. Can contain abstract methods (without implementation) and regular methods. Used to define common characteristics for subclasses.
abstract class AbstractClass { abstract void abstractMethod(); // Abstract method void regularMethod() { System.out.println("Regular method"); } } - Nested classes: Declared inside another class. Can be:
- Static nested classes: Do not have access to non-static members of the outer class. Created without an instance of the outer class.
class OuterClass { static class StaticNestedClass { // ... } } - Inner classes: Have access to all members of the outer class (including private). Are linked to an instance of the outer class.
class OuterClass { class InnerClass { // Has access to OuterClass members } } - Local classes: Declared inside a method, loop, or if block. Access is limited to their scope.
class OuterClass { void someMethod() { class LocalClass { // Declared locally } LocalClass obj = new LocalClass(); } } - Anonymous classes: Without a name, created simultaneously with declaration or instantiation. Used for one-time use.
interface MyInterface { void myMethod(); } MyInterface anon = new MyInterface() { @Override public void myMethod() { System.out.println("Anonymous class"); } };
- Static nested classes: Do not have access to non-static members of the outer class. Created without an instance of the outer class.
- Record classes (Java 14+): Concise syntax for declaring immutable classes intended for data storage (POJO).
record Person(String name, int age) { // Constructor, getters, equals(), hashCode(), toString() are auto-generated }