Hello All,
I must admit that I have been a manual tester and have just begun swimming through java (for selenium tool) I got to know that protected members of a class would be accessible in derived class. Despite this I created instance of base class in derived class and tried to access protected members (I agree that it sounds foolish as I can directly access protected members in derived class with out instantiating base class but still....). So whole scenario is -
Base class -
package com.core;
public class MyCollection {
protected Integer intg;
}
A derived class in the same package -
package com.core;
public class MyCollection3 extends MyCollection {
public void test(){
MyCollection mc = new MyCollection();
mc.intg=1; // Works
}
}
A derived class in a different package -
package secondary;
import com.core.MyCollection;
public class MyCollection2 extends MyCollection{
public void test(){
MyCollection mc = new MyCollection();
mc.intg = 1; //!!! compile time error - change visibility of "intg" to protected
}
}
I am wondering how it is possible to access a protected member of a base class in a derived class using instance of base class when derived class is also in same package, but not when derived class is in different package.
Herein if I mark protected member as "static" then I am able to access protected member of base class using instance of base class in a derived class which resides in a different package (Though at this point I could have access it using class name itself instead of creating instance of base class)