我正在尝试使用Object类Reference变量访问来自student和customer类的不同类的类成员,即getDetails()。但看起来它不起作用。请查看这个简单的代码,并帮助我使用Object类ob [0]和ob [1]
访问getDetails()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();
}
}
答案 0 :(得分:1)
尝试创建一个声明方法getDetails的通用接口。像这样:
public interface Person {
public void getDetails();
}
让学生和客户实施界面。然后像这样声明数组:
Person ent[] ob = new Person[2];
....