In Java, class methods are functions defined within a class that describe the behaviors or actions that objects of the class can perform. These methods can manipulate object data, perform operations, and return results. Understanding class methods is crucial for implementing object-oriented programming in Java.
Types of Class Methods
Instance Methods: These methods operate on instances (objects) of a class. They can access instance variables and other instance methods directly.
Static Methods: These methods belong to the class rather than any particular object. They can be called without creating an instance of the class and can only directly access static variables and other static methods.
Syntax
Instance Method
public returnType methodName(parameters){// method body}Được hỗ trợ bởi
Static Method
publicstatic returnType methodName(parameters){// method body}Được hỗ trợ bởi
returnType: The data type of the value returned by the method. Use void if the method does not return a value.
methodName: The name of the method, following Java naming conventions.
parameters: A comma-separated list of input parameters, each defined by a data type and name.
Examples
Example 1: Instance Method
publicclassCar{private String model;publicCar(String model){this.model = model;}publicvoiddisplayModel(){
System.out.println("Car model: "+ model);}publicstaticvoidmain(String[] args){
Car car =newCar("Toyota");
car.displayModel();}}Được hỗ trợ bởi
In this example, displayModel() is an instance method that prints the model of the car. It is called on an instance of the Car class.
Example 2: Static Method
publicclassMathUtils{publicstatic int add(int a, int b){return a + b;}publicstaticvoidmain(String[] args){
int result = MathUtils.add(5,3);
System.out.println("Sum: "+ result);}}Được hỗ trợ bởi
Here, add() is a static method that adds two integers. It is called using the class name MathUtils without creating an instance.
In Java, class methods are functions defined within a class that describe the behaviors or actions that objects of the class can perform. These methods can manipulate object data, perform operations, and return results. Understanding class methods is crucial for implementing object-oriented programming in Java.
Types of Class Methods
Syntax
Instance Method
Static Method
voidif the method does not return a value.Examples
Example 1: Instance Method
In this example,
displayModel()is an instance method that prints the model of the car. It is called on an instance of theCarclass.Example 2: Static Method
Here,
add()is a static method that adds two integers. It is called using the class nameMathUtilswithout creating an instance.Example 3: Method Overloading
This example demonstrates method overloading, where two
print()methods have the same name but different parameter types.Tips and Best Practices
public,private,protected) to control the visibility of methods.