-5

Why the reference type object o is not able to access variable a. It is showing error a can't be resolved or is not a field.

public class test2 {
int a;

public static void main(String args[]) {
    Object o = new test2();
    test2 t = new test2();
    t.a = 0;
    o.a = 10;


}
}
Aadi
  • 154
  • 1
  • 2
  • 18

2 Answers2

0

In Java, you can't create fields just by assigning to them. You must declare them in your code also:

public class test2 {
    int a;
    ...
}

Even then, if you declare a variable as an Object, that is really a "test2" instance, you still won't be able to access field 'a' without casting it first.

Object o = new test2();
o.a = 5  // compile error
test2 t = (test2)o;
t.a = 5 // ok. Will compile fine

The Java compiler keeps things fairly simple, meaning that it doesn't work hard to see if "o" is really a test2 or not, it just uses the declared class to determine which fields and methods are accessible.

Jeremy Gurr
  • 1,613
  • 8
  • 11
0

Basically, you are confused between reference type and instance (object) type.

In your program, o is the reference variable with type Object, so o will be able to access only the methods and variables from Object class. Also, t is the reference variable with type test2, so t can access class members of test2. You can look here for more details.

In short, reference type decides which members of the class you can access.

Also, look at the below popular classes for Inheritance to understand the above concept:

public class Animal {
   public String foodtype;
   //other members
}

public class Dog extends Animal {
   public String name;
   //other members
}

public class Test {

   public static void main(String[] args) {
        Animal a = new Dog();//'a' can access Anmial class members only
        a.foodtype = "meat"; //ok
        a.name = "puppy"; //compiler error

        Dog d = new Dog();//'d' can access both Animal and Dog class members
        d.foodtype = "meat"; //ok
        d.name = "puppy";//ok
   }
}
Community
  • 1
  • 1
Vasu
  • 21,832
  • 11
  • 51
  • 67