Defining Classes
In Java, a class serves as a blueprint for creating objects. It encapsulates data (fields) and behavior (meethods) into a single unit. A basic class structure is defined as follows:
class Employee {
String name;
int age;
}
Instantiating Objects
To use a class, you must create an instance of it using the new keyword. This allocates memory for the object on the heap.
Employee emp = new Employee();
Member Variables and Access Control
Fields within a class define the state of the object. Java provides access modifiers (such as private, public, and protected) to control the visibility of these variables. Best practices dictate keeping fields private and providing access via public getter and setter methods.
Reference Semantics
Object variables in Java act as references. When you assign one object variable to another, both point to the same memory address. If a reference is reassigned and no longer points to an object, that object becomes eligible for garbage collection by the JVM.
Defining Methods
Methods define the behavior of an object. Within a class, you can access instance variables directly. If a method parameter shares the same name as a member variable, you must use the this keyword to explicitly reference the class instance variable.
public void setName(String name) {
this.name = name;
}
Method Overloading vs. Overriding
Overloading (Static Polymorphism): Occurs when mlutiple methods in the same class share the same name but have different parameter lists (different number of parameters, different types, or a different sequence of types). The return type does not distinguish overloaded methods.
Overriding (Dynamic Polymorphism): Occurs in the context of inheritance. A subclass provides a specific implementation for a method that is already defined in its superclass, matching the method signature exactly.
Constructors
Constructors are specialized methods used to initialize objects. They must have the same name as the class and do not define a return type. If no constructor is defined, Java provides a default no-argument constructor.
class Project {
int id;
String title;
public Project(int id, String title) {
this.id = id;
this.title = title;
}
}
// Usage:
Project p = new Project(101, "Java Development");