Yes. A class definition will have its own variables (state), and will have its own methods (behavior).
// Define the Person class
public class Person {
// Attributes or instance variables
String name;
int age;
// Constructor to initialize Person objects
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to greet the person
public void greet() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
// Main class to demonstrate the usage of Person objects
public class Main {
public static void main(String[] args) {
// Creating objects of the Person class using the constructor
Person person1 = new Person("John", 25);
Person person2 = new Person("Alice", 30);
// Accessing object attributes and calling methods
person1.greet(); // Output: Hello, my name is John and I am 25 years old.
person2.greet(); // Output: Hello, my name is Alice and I am 30 years old.
}
}
Explanation:
Person class with two attributes: name and age. These attributes represent the state of a person object.Person(String name, int age) to initialize the attributes of a Person object when it is created.Person class has a method greet() that prints a greeting message including the person's name and age.Main class, we create two Person objects (person1 and person2) using the constructor. We provide specific values for the attributes of each person.greet() method of each Person object (person1 and person2) in the main method.This example illustrates the key concepts of OOP, including classes, objects, attributes, methods, and constructors, using Java programming language with a simpler example of a Personclass.
(Thought Question:) Is it possible for a program to have several objects all of the same class?