使用继承时如何创建对象?

因此,我拥有超类角色,以及子类Estudiante和Docente。 nombre,cedula,mail属性是我希望在Estudiante和Docente上拥有的属性,因为它们都具有它们,但是由于Estudiante和Docente都是Persona的属性,因此我可以使用继承。所有这些对象都有其get / set和tostring方法。 我发布的最后一个代码是我拥有的UI。我想按下一个按钮并创建一个Estudiante,但是我不能,因为它告诉我即时通讯提供了我可以提供的更多参数,所以我该怎么做?我希望我能很好地解释自己。

由于我真的不知道该尝试什么,所以我没有尝试过任何东西。 我第一次编写该代码时,我并没有考虑过使用这种超类Persona,但被告知我绝对必须那样做。

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);

在这种情况下,我希望创建一个Estudiante,但我也将创建Docente,然后由这两个团队中的许多人组成团队,但是我不能因为im给出的论点过多而已。

huangqibing1987 回答:使用继承时如何创建对象?

在每个类中,您还需要有一个构造函数-基本上是用来定义如何创建这些对象之一的构造函数。像这样:

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*/
    }
}

但是当您进入 child 类(即Estudiante和Docente)时,可以在构造函数内部使用super()方法,该方法将在调用时运行父类的构造函数。

Give this a read too.

本文链接:https://www.f2er.com/3134214.html

大家都在问