我已經宣告了一個具有母型別別的表,并且我已經用許多具有擴展型別別的物件填充了它,一切看起來都很好并且表已成功填充,問題是當我試圖訪問表值我不能(在示例中我試圖獲得薪水屬性)
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();
}
}
}
}
uj5u.com熱心網友回復:
您已經告訴編譯器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();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/464911.html
