Java Program - Using Methods (setValue)¶
Concept Explanation¶
What is it?¶
Methods are blocks of code that perform a specific task. A setValue method (often called a "setter") is used to assign values to class fields after an object has been created.
Why is it important?¶
It promotes modularity. Instead of putting all logic in main, you separate data assignment into dedicated methods.
Implementations¶
class Car {
String model;
int year;
// Method to set values
void setValues(String m, int y) {
model = m;
year = y;
}
void display() {
System.out.println("Car Model: " + model);
System.out.println("Year: " + year);
}
}
public class MethodDemo {
public static void main(String[] args) {
Car myCar = new Car();
// Calling the method
myCar.setValues("Toyota Camry", 2022);
myCar.display();
}
}
Explanation¶
- Parameters:
String mandint yare local variables. - Assignment: Inside the method,
model = mcopies the value from the parameter to the instance variable. - Separation: This approach separates creation (
new Car()) from initialization (setValues).
Related Concepts¶
- Using Constructors (Alternative way to initialize)
- Encapsulation (Using setters with validation)