2016-10-09 76 views
0

我試圖訪問不同類的類成員,即getDetails()從學生以及客戶類使用對象類引用變量。但它看起來不起作用。請看看這個簡單的代碼,並使用Object類OB [0]和OB [1]使用Object類引用變量,訪問不同的類成員。

class Customer 
{ 
    int custId; 
    String name; 
    Customer(String name, int custId) 
    { 
     this.custId = custId; 
     this.name = name; 
    } 

    public void getDetails() 
    { 
     System.out.println(this.custId+" : "+this.name); 
    } 

} 
class Student 
    { 
     int roll; 
     String name; 
     Student(String name, int roll) 
     { 
      this.name = name; 
      this.roll = roll;  
     } 
     public void getDetails() 
     { 
      System.out.println(this.roll+" : "+this.name); 
     } 
     public static void main(String []args) 
     { 
      Object[] ob = new Object[2]; 
      ob[0] = new Student("Vishal", 041); 
      ob[1] = new Customer("Xyz" , 061); 
      ob[0].getDetails(); 
      ob[1].getDetails(); 
     } 
    } 

回答

1

嘗試創建聲明的方法getDetails的通用接口幫助我如何訪問getDetails()。類似這樣的:

public interface Person { 
    public void getDetails(); 
} 

讓學生和客戶實現該接口。然後聲明這樣的數組:

Person ent[] ob = new Person[2]; 
.... 
相關問題