Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

¿Como puedo hacer un metodo constructor? JAVA

0 votes
asked Apr 4, 2022 by Keyra Arlette Ruiz Hernandez (120 points)
Ya que al intentar hacerlo siempre sale el mismo error, me gustaria conocer como solucionarlo. Si me pueden ayudar se los agradeceria mucho.  https://onlinegdb.com/ed5d4mPtY3

1 Answer

0 votes
answered Apr 9, 2022 by Peter Minarik (86,040 points)

First of all, your main() method should be spelt with a lower case 'm', and not uppercase 'M'.

Your Persona class does not work correctly.

public class Persona
{
    //Atributos
    String nombre;
    int edad;

    //Metodo constructor
    public Persona(String nombre, int edad)
    {
        nombre = nombre;
        edad= edad;
    }

    public void mostrarDatos()
    {
        System.out.println("Mi nombre es: " + nombre);
        System.out.println("Mi edad es: " + edad);
    }
}

The problem is that in the constructor your assign the value of a variable to itself (effectively doing nothing):

nombre = numbre;

Probably what you wanted to do is set the value of the numbre field (atributos) to be equal to the parameter numbre passed into the constructor. Other object-oriented programming languages allow you to use the this keyword to differentiate between class fields and local variables, however, Java does not allow you to do this.

So, the most simple solution is not to call your constructor parameters the same as your fields. E.g. add a trailing underscore (_) after every field name if it would normally be the same as existing fields:

public Persona(String nombre_, int edad_)
{
    nombre = nombre_;
    edad= edad_;
}

Good luck!

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...