Understanding Classes and Objects
Class Definition
class ClassName {
DataType variableName;
// Multiple declarations can be present here
}
Object Instantiation
ClassName objectName = new ClassName(); // Whether parameters are required depends on the constructor method
Member Variables
In a class, variables can have different access levels. For example:
class TestClass {
String testVar = "value"; // Default access modifier (public), can be accessed and modified
private int privateVar = 0; // Private access modifier, cannot be accessed directly from outside the class
}
Access and modify member variables using the syntax
ClassName.variableName.
Reference Nature
Similar to array names, object names are references. When a variable is assigned to an object, the previous object becomes eligible for garbage collection by Java's JVM garbage collector.
Member Functions
Just as we can write methods in the main method, we can also define methods in custom classes. However, it's important to understand variable scope.
Inside a class, methods can access class members directly. However, if a parameter has the same name as a member variable, use
this.memberVariable to specify the member.
Functions with Return Types
ReturnType methodName(DataType param, DataType1 param1) {
// Method body
return value; // Must match the return type
}
Method Overloading and Overriding
Method Overloading
Method overloading requires either:
- Different number of parameters
- Same number of parameters but different types
- Same parameter types in different order
Return types can be the same or different. Return type alone cannot be used to distinguish overloaded methods. This is also known as static polymorphism.
Method Overriding
Method overriding occurs in inheritance relationships when a subclass defines a method identical to one in its superclass (same parameter names, types, count, and return type).
Polymorphism
Generally, an object can be referenced by a single name, and overloaded methods with the same name can be invoked to perform different functions.
Constructors
- Constructor name must match the class name
- No return type
- Used for initialization when creating instances
class TestClass {
int number;
String name;
// Default constructor
TestClass() {
number = 1;
name = "Default Name";
}
// Parameterized constructor
TestClass(int n, String name) {
this.number = n;
this.name = name;
}
}
// Usage
TestClass obj1 = new TestClass(); // number=1, name="Default Name"
TestClass obj2 = new TestClass(2, "Custom Name"); // number=2, name="Custom Name"