I have the following code in Java
public class First {
protected int z;
First()
{
System.out.append("First const");
}
}
class Second extends First {
private int b;
protected int a;
}
class Test {
/**
* @param args the command line arguments
*/
int a=0;
public static void main(String[] args) {
// TODO code application logic here
First t=new Second();
t.z=10; work fine
First x=new First();
x.z=1; // works fine
}
}
so I can access z
by creating object of base
class
C#
class A
{
protected int x = 123;
}
class B : A
{
static void Main()
{
A a = new A();
B b = new B();
// Error CS1540, because x can only be accessed by
// classes derived from A.
// a.x = 10;
// OK, because this class derives from A.
b.x = 10;
}
}
So i cannot access a
, if through base class object. I found Java and C# similar from an OOP
point of view, is there any difference between both languages for protected
members?
The difference is that in java a protected member can be accessed from the same package. In C++ there is no equivalence for package level visibility in java.