Intern
What are the parts of a class in Java?
sobes.tech AI
Answer from AI
In Java, a class typically consists of the following parts:
- Access Modifiers: Define where the class is accessible from (e.g.,
public,protected,private, or no modifier). - Keyword
class: Mandatory element for declaring a class. - Class Name: The identifier of the class, usually following PascalCase conventions.
- Keyword
extends(optional): Indicates the superclass from which this class inherits. - Keyword
implements(optional): Indicates the interfaces that this class implements. - Class Body
{}: Contains the class members.
Inside the class body, there can be:
- Fields: Variables of the class representing its state. They can have access modifiers, be static (
static), and final (final). - Constructors: Special methods for initializing class objects. They have the same name as the class and no return type. They can be overloaded.
- Methods: Functions defining the behavior of the class. They can have access modifiers,
static,final,abstractmodifiers, a return type, name, and parameters. - Initialization Blocks: Code blocks executed when creating an object (non-static) or when loading the class (static).
// Non-static initialization block { // Code executed when each object is created }// Static initialization block static { // Code executed when the class is loaded } - Inner Classes: Classes declared within another class. They can be non-static, static (nested), local, or anonymous.