In Java, a class and an object are fundamental concepts in object-oriented programming. Let's explore what each term means:
class
keyword, followed by the class name and the class body that contains the attributes and methods.Example of a simple class in Java:
public class Person {
// Attributes
String name;
int age;
// Method
public void sayHello() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
Creating and using objects in Java:
public class Person {
// Attributes
String name;
int age;
// Method
public void sayHello() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
public class Main {
public static void main(String[] args) {
// Create objects of the Person class
Person person1 = new Person();
Person person2 = new Person();
// Set attribute values for each object
person1.name = "Alice";
person1.age = 30;
person2.name = "Bob";
person2.age = 25;
// Call methods on the objects
person1.sayHello(); // Output: Hello, my name is Alice and I am 30 years old.
person2.sayHello(); // Output: Hello, my name is Bob and I am 25 years old.
}
}
In summary, a class defines the blueprint or template for creating objects, and an object is a concrete instance of that class with its own data and behavior. Objects allow you to model real-world entities and interact with them in your Java programs.