jvm 从母类对象打印扩展类对象的值

3phpmpom  于 2022-11-07  发布在  其他
关注(0)|答案(1)|浏览(135)

我已经声明了一个具有母类类型的表,并且我已经用许多具有扩展类类型的对象填充了它,一切看起来都很好,表被成功填充,问题是当我试图访问表值时,我不能(在这个例子中,我试图获得 salaire attribut)

母级

package TP4_exo2;

     public class personne {
        private String nom,prenom,date_de_naissance;

        public personne(){}
        public personne(String nom, String prenom, String date_de_naissance) {
            this.nom = nom;
            this.prenom = prenom;
            this.date_de_naissance = date_de_naissance;
        }

        public void affiche() {
            System.out.println("\nnom :"+this.nom+
                    "\nprenom :"+this.prenom+
                    "\ndate de naissance :"+this.date_de_naissance);
        }
    }

子类别1

package TP4_exo2;

public class employé extends personne {

   Double salaire;

   public employé() {
       super();
       salaire=0.0;
   }

   public employé(String nom, String prenom, String date_de_naissance,Double salaire) {
       super(nom,prenom,date_de_naissance);
       this.salaire=salaire;
   }

   public void affiche() {
       super.affiche();
       System.out.print("salaire :"+this.salaire);
   }

}

主类

package TP4_exo2;

    import java.util.Scanner;

    public class programme4 {

        public static void main(String[] args) {
            personne tab [] =  new personne[2];
            Scanner sc = new Scanner(System.in);
            int i,j;

            for(i=0;i<tab.length;i++) {

                personne emp1;//declaration

                System.out.println("Donner le nom "+i);//demande informations
                String nom = sc.next();
                System.out.println("Donner le prenom "+i);
                String prenom = sc.next();  
                System.out.println("Donner la date de naissance "+i);
                String date = sc.next();
                System.out.println("Donner le salaire "+i);
                Double salaire = sc.nextDouble();

                emp1 =  new employé(nom,prenom,date,salaire);//instanier l'obj avec ls info
                tab[i] = emp1;//affecter au tableau

            }

            for(i=0;i<tab.length;i++) {
                System.out.println("EMPLOYER "+i+"\n");

                if(tab[i].salaire>45000)**//Exception in thread "main" 
               //java.lang.Error: Unresolved compilation problem: 
               //salaire cannot be resolved or is not a field**
                {
                    tab[i].affiche();
                }
            }

        }

    }
nhaq1z21

nhaq1z211#

您已经告诉编译器tab包含personne对象。编译器只知道您告诉它的内容。
编译器不会执行你的程序,它不知道你的程序可能已经在数组中添加了一个employé示例,因此,它不会跟踪你程序中的每个方法调用,检查这些方法是否添加了不同的对象。
由于编译器只能确定tab包含personne类型的对象,或者可能是它的子类型,因此您必须自己检查每个元素的类型:

if (tab[i] instanceof employé emp && emp.salaire > 45000)
{
    tab[i].affiche();
}

如果您使用的Java版本早于Java 14,则必须手动执行转换:

if (tab[i] instanceof employé)
{
    employé emp = (employé) tab[i];
    if (emp.salaire > 45000)
    {
        tab[i].affiche();
    }
}

相关问题