2016-10-09 73 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]; 
.... 
相关问题