Create a Book class and an object from it in Java using the Main method with OOP.

Advertisement

Create a class called Book that represents a book in a library. The class must have the following private attributes:

Title (String): title of the book
Author (String): name of the author of the book
Number of Pages (int): number of pages the book has
Available (boolean): indicates whether the book is available for loan

The class should include:

A constructor that accepts the title, author, and page count as parameters. The book must be initialized as available (true).

Methods getter for all attributes.
A lend() method that changes the availability state to false if the book is available, and returns true. If the book is not available, the method should not change the state and should return false.
A return() method that changes the availability status to true if the book is not available, and returns true. If the book is already available, the method should not change the status and should return false.
A toString() method that returns a string with the book information in the format: “[Title] written by [Author] – [Number of pages] pages. [Available/Not available]”.
Finally, in the main method, creates an object of the Book class, displays its information, lends it, displays its updated information, and returns it.

Advertisement
package oop.Libros;

// codificado por Javier Cachón Garrido en MX-Linux con IntelliJ IDEA Community Edition .

public class Libro {

        // Atributos privados
        private String titulo;
        private String autor;
        private int numeroPaginas;
        private boolean disponible;

        // Constructor
        public Libro(String titulo, String autor, int numeroPaginas) {
            this.titulo = titulo;
            this.autor = autor;
            this.numeroPaginas = numeroPaginas;
            this.disponible = true; // Se inicializa como disponible
        }

        // Métodos getter
        public String getTitulo() {
            return titulo;
        }

        public String getAutor() {
            return autor;
        }

         public int getNumeroPaginas() {
            return numeroPaginas;
         }

        public boolean isDisponible() {
            return disponible;
        }

        // Método prestar
        public boolean prestar() {
            if (disponible) {
                disponible = false;
                return true;
            } else {
                return false;
            }
        }

        // Método devolver
        public boolean devolver() {
            if (!disponible) {
                disponible = true;
                return true;
            } else {
                return false;
            }
        }

        // Método toString para mostrar la información del libro
        @Override
        public String toString() {

            String estado = disponible ? "Disponible" : "No disponible";
            return titulo + " escrito por " + autor + " - " + numeroPaginas + " páginas. " + estado;
        }

        public static void main(String[] args) {
            // Crear un objeto de la clase Libro
            Libro libro = new Libro("Libro de Java a fondo", "Javier Cachón Garrido", 1000);

            // Mostrar información inicial
            System.out.println("Información del libro:");
            System.out.println(libro.toString());

            // Prestar el libro
            System.out.println("Intentando prestar el libro...\n");
                if (libro.prestar()) {
                    System.out.println("Libro prestado con éxito.");
                } else {
                    System.out.println("El libro no está disponible para préstamo.");
                }

            // Mostrar información después de prestarlo
            System.out.println("Información actualizada:\n");
            System.out.println(libro.toString());

            // Devolver el libro
            System.out.println("Intentando devolver el libro...\n");
                if (libro.devolver()) {
                    System.out.println("Libro devuelto correctamente.");
                } else {
                    System.out.println("El libro ya estaba disponible.");
                }

            // Mostrar información final
            System.out.println("Información final del libro:\n");
            System.out.println(libro.toString());
    }

}

Execution result and compilation in ok:

Información del libro:
Libro de Java a fondo escrito por Javier Cachón Garrido - 1000 páginas. Disponible
Intentando prestar el libro...

Libro prestado con éxito.
Información actualizada:

Libro de Java a fondo escrito por Javier Cachón Garrido - 1000 páginas. No disponible
Intentando devolver el libro...

Libro devuelto correctamente.
Información final del libro:

Libro de Java a fondo escrito por Javier Cachón Garrido - 1000 páginas. Disponible

Process finished with exit code 0

Feedback and suggestions

The presented solution meets all the requirements of the statement. The Book class is correctly implemented with private attributes, and the constructor properly initializes the availability status. The getter methods provide access to the attributes, and the borrow() and return() methods correctly manage the book's availability status. The toString() method returns the book information in the specified format. Furthermore, the main method demonstrates the use of the Book class in a clear and functional manner. The code structure is clear and follows Java conventions, making it easy to read. Congratulations on a precise and complete implementation!

Open Source License: GPL: You can improve it, but it is not for commercial or business use, but for educational purposes.

Our score
Click to rate this post!
(Votes: 0 Average: 0)
Advertisement
Share on social media...

Deja un comentario

Your email address will not be published. Required fields are marked *

Basic information on data protection
ResponsibleJavier Cachón Garrido +info...
PurposeManage and moderate your comments. +info...
LegitimationConsent of the concerned party. +info...
RecipientsAutomattic Inc., USA to spam filtering. +info...
RightsAccess, rectify and cancel data, as well as some other rights. +info...
Additional informationYou can read additional and detailed information on data protection on our page política de privacidad.

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.

Scroll al inicio

Descubre más desde javiercachon.com

Suscríbete ahora para seguir leyendo y obtener acceso al archivo completo.

Seguir leyendo