Java Exercise
In this exercise, you will create a Java program that defines a class named Person
. This class will have attributes such as name
, age
, and address
, as well as a showInfo()
method that prints these attributes. You will then instantiate at least two objects of the Person
class and use the method to display information for each one.
Instructions:
- Create a class named
Person
with the attributes name
, age
, and address
.
- Add a
showInformation()
method that prints the class attributes.
- In the main method, create two objects of the
Person
class and assign values to their attributes.
- Call the
showInformation()
method for each object and display the information in the console.
This exercise will help you understand how to work with classes and objects in Java, allowing you to create more organized and reusable structures in your programs.
View Example Code
public class Person {
// Attributes of the Person class
String name;
int age;
String address;
// Method to display the person's information
public void showInformation() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
public static void main(String[] args) {
// Create two objects of the Person class
Person person1 = new Person();
person1.name = "John";
person1.age = 30;
person1.address = "123 Fake Street";
Person person2 = new Person();
person2.name = "Anna";
person2.age = 25;
person2.address = "456 Always Live Avenue";
// Display the information of each person
person1.showInformation();
System.out.println();
person2.showInformation();
}
}
Output:
Name: John
Age: 30
Address: 123 Fake Street
Name: Anna
Age: 25
Address: 456 Always Live Avenue
This program creates two objects of the Person
class, assigns values to their attributes, and displays information about each using the showInformation()
method.