about writing methods

2

I have the following code and when I try to write the method rellenarTipo I get an error, I have created a main class called main and another class called subclase that inherits main where when @Override is when it tells me error

public class main {

    public static void main(String[] args) {
        rellenarTipo();
    }
    public static void rellenarTipo() {
        String dni, nombre;
        Scanner scan = new Scanner(System.in);

        System.out.println("introduza nombre");
        nombre = scan.next();
        System.out.println("introduzca dni");
        dni = scan.next();
    }
}

And this is the subclass that inherits from the class main and where I want to escirbir fill type, someone guides me a bit to know what I do wrong?

public class SubClase extends main {
    int edad;
    @Override
    public static void rellenarTipo(){
        System.out.println("introduzca edad");
    }
}
    
asked by spain21 20.02.2016 в 16:00
source

1 answer

2

In Java, the static methods static can not be overwritten since the static members belong to the class, not to the instances of the class. You must declare non-static methods for it.

Your class should look like this:

public class main {

    public static void main(String[] args) {
        main m = new main();
        m.rellenarTipo();
    }
    public void rellenarTipo() {
        String dni, nombre;
        Scanner scan = new Scanner(System.in);

        System.out.println("introduza nombre");
        nombre = scan.next();
        System.out.println("introduzca dni");
        dni = scan.next();
    }
}

public class SubClase extends main {
    int edad;
    @Override
    public void rellenarTipo() {
        System.out.println("introduzca edad");
    }
}

Also, if you want to save data for your class, these should not be local variables to the methods, but should be class fields. Then, the design of your classes should look like this:

public class main {
    String dni, nombre;
    protected static Scanner scan;
    public static void main(String[] args) {
        main m = new Subclase();
        m.rellenarTipo();
    }
    public void rellenarTipo() {
        scan = new Scanner(System.in);
        System.out.println("introduza nombre");
        this.nombre = scan.next();
        System.out.println("introduzca dni");
        this.dni = scan.next();
    }
}

public class SubClase extends main {
    int edad;
    @Override
    public void rellenarTipo() {
        System.out.println("introduzca edad");
        this.edad = scan.nextInt();
    }
}
    
answered by 20.02.2016 / 18:23
source