about method writing
I have the following code and when I try about writing method rellenarTipo
it gives me error,I have created a parent class called main
and another class called subclase
which inherits from main
where when I put @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 about scirbir fill type, someone guides me a little to know that I do wrong?
public class SubClase extends main {
int edad;
@Override
public static void rellenarTipo(){
System.out.println("introduzca edad");
}
}
1 answers
In Java, static methods static
they cannot be overwritten since static members belong to the class, not to 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 variables local to the methods, but should be class fields. So the layout 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();
}
}