Classes
Definition
- Class: A blueprint for creating objects. It defines a type of object according to the data it holds and the methods that manipulate the data.
Class Structure
- Class Declaration:
class ClassName { ... }
- Class Name: Should be a noun, capitalized first letter.
- Modifiers: Can include
public
,private
,abstract
,final
.
Components of a Class
- Fields: Variables within a class.
- Example:
int age;
- Example:
- Methods: Functions within a class.
- Example:
void display() { ... }
- Example:
- Constructors: Special methods to initialize objects.
- Example:
ClassName() { ... }
- Example:
- Blocks: Initialization blocks for setting up the class state.
Access Modifiers
- Public: Accessible from any other class.
- Private: Accessible only within the class it is defined.
- Protected: Accessible within the same package and subclasses.
- Default (no modifier): Accessible only within the same package.
Method Overloading
- Defining multiple methods with the same name but different parameters.
- Example:
void display() { ... } void display(int x) { ... }
- Example:
Constructors
- Default Constructor: No parameters, initializes default values.
- Parameterized Constructor: Takes parameters to initialize fields.
- Example:
ClassName(int x) { ... }
- Example:
Inheritance
- Single Inheritance: A class inherits from one superclass.
- Example:
class SubClass extends SuperClass { ... }
- Example:
- Method Overriding: Redefining a superclass method in a subclass.
- Example:
@Override void display() { ... }
- Example:
Encapsulation
- Bundling data (fields) and methods operating on the data into one unit.
- Use of private fields and public getter/setter methods to control access.
- Example:
private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; }
- Example:
Polymorphism
- Compile-time Polymorphism: Method overloading.
- Runtime Polymorphism: Method overriding using inheritance.
Static Members
- Static Fields: Shared among all instances of a class.
- Example:
static int count;
- Example:
- Static Methods: Can be called without creating an instance of the class.
- Example:
static void displayCount() { ... }
- Example:
Nested Classes
- Inner Class: Defined within another class.
- Example:
class Outer { class Inner { ... } }
- Example:
- Static Nested Class: A static class within another class.
- Example:
class Outer { static class StaticNested { ... } }
- Example:
Abstract Classes
- Cannot be instantiated, used to define common characteristics.
- Example:
abstract class Animal { abstract void sound(); }
- Example:
Interfaces
- A reference type similar to a class that can contain only constants, method signatures, default methods, static methods, and nested types.
- Example:
interface Animal { void sound(); }
- Example:
By understanding these core concepts of Java classes, you can create and manage complex object-oriented programs efficiently.