Classes and Objects

In this exercise, you will learn how to create and use classes and objects in Java. You will discover how to organize your code into classes, instantiate objects, and manipulate their attributes and methods to develop more structured and efficient programs. Through practical exercises, you will improve your understanding of object-oriented programming (OOP) in Java, a key concept for writing clean and reusable code.

Topic

Object-Oriented Programming (OOP)

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:

  1. Create a class named Person with the attributes name, age, and address.
  2. Add a showInformation() method that prints the class attributes.
  3. In the main method, create two objects of the Person class and assign values ​​to their attributes.
  4. 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.


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.


 Share this JAVA exercise