Page 1 of 1

About Question com.enthuware.ets.scjp.v6.2.455 :

Posted: Tue Nov 15, 2011 1:41 pm
by stessy
Hi,

I don't understand this question.

Why cannot we access the instance variable when they are in different packages. While we can access the same variable when they are in the same package.

If B is not involved in the implementation of A, the behavior should be the same whether or not the classes are in the same package.

Code: Select all

package be.p2;

public class B extends A {
    public void process(A a) {
        a.i = a.i * 2;
    }

    public static void main(String[] args) {
        A a = new B();
        B b = new B();
        b.process(a);
        System.out.println(a.getI());
    }
}

package be.p2;

public class A {
    protected int i = 10;

    public int getI() {
        return i;
    }
}
This code works and "20" is printed.

Thanks a lot for you help.

Re: About Question com.enthuware.ets.scjp.v6.2.455 :

Posted: Tue Nov 15, 2011 2:25 pm
by admin
This is how the language has been designed. Class B inherits the protected fields and so it can access the inherited field through its own reference (because B has that field). But when you try to access A.i from class B, it fails because B does not have A's i. class B is not involved in the implementation of class A. class B is involved only in the implementation of class B (or its subclasses), so it can access its own fields including the ones that it inherited.


When both the class are in the same package, B can access A.i because protected is a lower protection level than pacakge and since any class in the same package can access A.i, B can also access it. The fact that B is a subclass of A is irrelevant in this case.

HTH,
Paul.

Re: About Question com.enthuware.ets.scjp.v6.2.455 :

Posted: Tue Nov 15, 2011 2:55 pm
by stessy
I thought that protected was higher than default access and protected could only be used for subclassing. That's the reason why I hadn't understood.

public --> protected --> default --> private

Thanks for this clarification.

Re: About Question com.enthuware.ets.scjp.v6.2.455 :

Posted: Sat Jan 19, 2013 10:25 am
by PMiglani
Hi,

I am not clear about the output of following program


class A
{
public int i = 15;
public int getI() { return i; }
}


public class B extends A
{
int i=8;
public void process(A a)
{
a.i = a.i*2;
i=i*3;
}
public static void main(String[] args)
{
A a = new B();
B b = new B();

b.process(a);


System.out.println( a.getI() );
System.out.println( a.i );
System.out.println( b.i );
System.out.println( b.getI() );
}
}


Output :-

30
30
24
15

Why b.getI() is displaying 15 ??

Thanks
Puneet

Re: About Question com.enthuware.ets.scjp.v6.2.455 :

Posted: Wed May 20, 2015 7:12 am
by pushpull
PMiglani wrote: Why b.getI() is displaying 15 ??
Because class B does not override the method getI()