Java is an object-oriented programming language that allows developers to create classes and objects. A class is a blueprint for creating objects, and it contains methods that define the behavior of the objects. Java class methods are the functions that are defined inside a class and are used to perform specific tasks. In this article, we will discuss Java class methods in detail.
Java class methods are used to perform specific tasks or operations on objects. These methods are defined inside a class and can be accessed by creating an object of that class. Java class methods can be classified into two types:
Instance methods are the methods that are called on an object of a class. These methods can access the instance variables of the object and can modify them. Static methods, on the other hand, are the methods that are called on the class itself. These methods cannot access the instance variables of the object and can only access the static variables of the class.
Let's take a look at some code examples of Java class methods:
public class Car {
private String color;
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.setColor("Red");
System.out.println(car.getColor());
}
}
In the above example, we have defined a class called Car that has an instance variable called color. We have also defined two instance methods called setColor and getColor that are used to set and get the color of the car object. In the main method, we have created an object of the Car class and set its color to "Red". We have then printed the color of the car object using the getColor method.
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}
}
public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 10);
int difference = MathUtils.subtract(10, 5);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
}
}
In the above example, we have defined a class called MathUtils that has two static methods called add and subtract. These methods are used to perform addition and subtraction operations on two integers. In the main method, we have called these methods using the class name and printed the results.
Java class methods are an important part of object-oriented programming in Java. They are used to define the behavior of objects and perform specific tasks. In this article, we have discussed the two types of Java class methods, instance methods and static methods, and provided some code examples. By understanding Java class methods, developers can create more efficient and effective Java programs.