我正在尝试使用对象类引用变量访问不同类的类成员,即学生类和客户类的 getDetails() 。但看起来它不起作用。请查看这个简单的代码并帮助我了解如何使用对象类 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();
}
}
最佳答案
尝试创建一个声明 getDetails 方法的通用接口(interface)。像这样的事情:
public interface Person {
public void getDetails();
}
让学生和客户实现该接口(interface)。然后像这样声明数组:
Person ent[] ob = new Person[2];
....
关于java - 使用Object类引用变量,访问不同的类成员。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39938685/