Question

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?

with reference to this doc

Était-ce utile?

La solution

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.

Autres conseils

I agree with the answer of tibtof. The only remark that i have is that your Java example is not the same as the C# example.

You can make the two codes similar by putting the "public static void main..." method of your Test class in class Second, deleting the Test class and make Second public.

The result is the same as your results: it works in Java but not in C#.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top