Bala
Bala

Reputation: 45

Java default access specifier is accessible outside the package?

I tried following piece of program and I came to know we can access default/package level instance variable.

I want to understand why it is allowed in java.

1.

package com.test;

class A {
    public int i = 10;
}

2.

package com.test;

public class B extends A{
}

3.

package com.child;

import com.test.B;

public class C extends B{

    public int getI(){
        return this.i;
    }

    public static void main(String[] args) {
        System.out.println(new C().getI());
    }
}

I'm able to run this program successfully. What I want to understand is how it possible to access default access variable from another packkage.

Upvotes: 0

Views: 476

Answers (3)

ZhongYu
ZhongYu

Reputation: 19682

B inherits all public members from A, regardless A's own visibility. That's why C sees the member too.

This is of course quite confusing. The root problem is that a public class extends a non-public class. Maybe the language should forbid that.

Upvotes: 0

Miloš Lukačka
Miloš Lukačka

Reputation: 842

there are 4 different access levels: public, private, protected and package-private. Public is visible to everything, outside package even. Private is visible only inside class. Protected is visible to class and to all classes, that extends it. Package-private is default (when you don't specify any of others), and it is visible to all classes within one package, where the variable is initialized

Upvotes: -1

Rylander
Rylander

Reputation: 20129

Because it extends B which extends A.

Upvotes: 2

Related Questions