Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to use the get and set with the toString but isn't working and I don't know why.
Can someone try to just explaing without saying the answer.

thanks on advance

What I have tried:

public class Main extends Livro{

    public static void main ( String Args[] ){

        Livro l1 = new Livro();
        l1.setTitulo("Harry Potter e a Pedra Filosofal");
        l1.setIsbn(978972232);
        l1.setAutor("J. K. Rowling");
        l1.setPaginas(260);

        Livro l2 = new Livro();
        l2.setTitulo("Harry Potter e a Pedra Filosofal");
        l2.setIsbn(978972232);
        l2.setAutor("J. K. Rowling");
        l2.setPaginas(260);

        System.out.println(l1.toString());
    }
    public String toString(){

        return "O livro com título " + getTitulo() + " e " + getIsbn() + " e autor " + getAutor() + " tem " + getPaginas() + "páginas";
        
    }
Posted
Updated 20-Jul-22 9:53am
v2
Comments
Richard MacCutchan 20-Jul-22 10:42am    
That is Java code, not Javascript.

There's a few problems here. First, why is your Main class extending the Livro class? Typically the class containing the main() method shouldn't really extend anything.

Second, and a by-product of the first point, you've overridden the toString() method in the Main class, not in the Livro class (from what I can tell). So in your code you're creating instances of Livro:
Java
Livro l1 = new Livro();

But I hazard a guess that you've not overridden the toString() method in that class. You need to move the toString() method into the Livro class (and also annotate it with @Override, many IDEs will wag their fingers at you for not annotating it). For example:
Java
public class Livro {

  ... your getters and setters ...

  @Override
  public String toString() {
    return "....";
  }
}

Do be aware that you need to define/override methods inside the classes that you're using, you can't just put the toString() method anywhere and expect it to work :)
 
Share this answer
 
also the same effect you get by this change:
//Livro l1 = new Livro();
  Livro l1 = new Main();

but I recommend solution 1
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900