java - 使用Object类引用变量,访问不同的类成员。

标签 java object

我正在尝试使用对象类引用变量访问不同类的类成员,即学生类和客户类的 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/

相关文章:

python - 在 Python 中引用另一个枚举作为枚举值?

vb.net - .IndexOf 函数在 vb.net 中为类列表返回负数

java - com.mysql.jdbc.MysqlDataTruncation : Data truncation: Incorrect datetime value: '0000-00-00 00:00:00' for column 'lastchange' at row 1

java - 修改Spring boot Embedded Tomcat解压路径

java - 静态方法和多态性

javascript - 在对象 `this` 中使用 "Unexpected token this"

javascript - 如何使用变量引用对象

java - Android空白 Activity 上的ClassNotFoundException

java - 在 Mapper 中检索当前行的文件名

arrays - Swift:如何检查对象是否在数组中?