Access data member of a class with reference of type 'Object'

Rahul Soni :

I have tried accessing the data member of a class Student via reference of 'Object' class (which is a base class of all classes in Java) but, the compiler throws a compile-time error.

Code:

class Student {
  String name;
  int roll;
  public Student(String name, int roll) {
    this.name = name;
    this.roll = roll;
  }
}

class Main {
  public static void main(String[] args) {
    Object ob[] = new Object[4];
    Student s = new Student("Yash", 88);
    ob[0] = s;

    System.out.println(s.name);
    System.out.println(ob[0].name);
  }
}

Output (Compile-time Error):

Main.java:19: error: cannot find symbol
    System.out.println(ob[0].name);
                            ^
  symbol:   variable name
  location: class Object
1 error
compiler exit status 1

Both, the instance as well as the pointer belong to same class:

System.out.println(s.getClass());
System.out.println(ob[0].getClass());

Output:

class Student
class Student
Rigo Sarmiento :

tldr; You'll still need to cast it:

System.out.println(((Student)ob[0]).name);

When you were trying ob[0].name you were seeing it before compile time. Since it hasn't been compiled, the compiler doesn't know yet that it is of type Student. But after compiling it, the runtime variable changes when you call ob[0]=s, which is why ob[0].getclass() works.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328428&siteId=1