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
}
}
solved The Object class is the parent class of all the classes in java by default