Search code examples
javaclassuser-interfacesuper

How do i create objects when working with inheritance?


So, i have the superclass Persona, and subclasses, Estudiante and Docente. The attributes nombre,cedula,mail are attributes that i wanted to have on Estudiante and Docente because they both have them, but since both Estudiante and Docente are Persona's, i can use inheritage. All these objects have their get/set and tostring methods. The last code i posted, is an UI that i have. I want to press a button and create an Estudiante, but i cant, because it tells me that im giving more arguments that the ones that i can give, so.. how do i do it? I hope i explained myself well.

I haven't tried anything since i don't really know what to try. The first time i wrote that code i didnt thought about using this super class Persona, but i was told that i absolutely have to do it like that.

public class Estudiante extends Persona{
    private int numero;
    private int semestre;
public class Docente extends Persona {    
    private int anoingreso;
public class Persona {
    private String nombre;
    private int cedula;
    private String mail;
private void BotonCrearEstudianteActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        Estudiante=new Estudiante(NombreEstudiante,CedulaEstudiante,MailEstudiante,NumeroEstudiante,SemestreEstudiante);

I expect to create an Estudiante in this case, but im going to create Docente's too, and later make teams with many of those two, but i can't because im giving too many arguments as i stated before.


Solution

  • Inside each class you also need to have a constructor- basically what you use to define how one of those objects is created. Like this:

    public class Persona{
        private String nombre;
        private int cedula;
        private String mail;
    
    
        public Estudiante(/*Insert the parameters you need, but do not call them by the same thing as your instance variables above*/){
           /*this block will execute when you create an Estudiante object*/
        }
    }
    

    But when you get to the child classes (i.e. Estudiante and Docente), you can use the super() method inside the constructor, which on call will run the parent class' constructor.

    Give this a read too.