In Java, both classes and objects can have methods.
Methods are functions that define the behaviour or actions that objects of a class can perform.
Here's a comparison between class methods and object methods in Java:
Class methods, also known as "static" methods, are associated with the class itself rather than with any particular instance of the class.
They are declared using the "static" keyword.
Class methods can be called using the class name, without creating an object of the class.
Class methods can access static variables and other class methods directly.
class YourClass { // Class variable private static int count = 0; // Class method public static void incrementCount() { count++; } // Another class method public static int getCount() { return count; } } public class Main { public static void main(String[] args) { System.out.println(YourClass.getCount()); YourClass.incrementCount(); System.out.println(YourClass.getCount()); } }
class Vehicle { // Instance variables private String manufacturer; private String model; // Constructor Method with Paramters public Vehicle(String manufacturer, String model) { this.manufacturer = manufacturer; this.model = model; } // Object method public void displayDetails() { System.out.println("Manufacturer: " + manufacturer); System.out.println("Model: " + model); } } public class Main { public static void main(String[] args) { Vehicle yourVehicle = new Vehicle("Land Rover", "Defender"); yourVehicle.displayDetails(); } }
Vehicle yourVehicle = new Vehicle("Land Rover", "Defender"); yourVehicle.displayDetails();
Object methods, also known as instance methods, are associated with individual objects (instances) of a class.
They are declared without the "static" keyword.
Object methods can access instance variables and other object methods directly using the "this" keyword.
Object methods are typically called on specific objects (instances) of the class.
To call an object method, We need to create an instance of the class and then call the method on that instance:
class methods are associated with the class itself and are called using the class name, while object methods are associated with individual objects of the class and are called on specific instances of the class.
Both types of methods are essential for defining the behaviour of classes and objects in Java.