tags:

views:

127

answers:

3

Please see the code below :

package bk;

public class A { 
    protected void methodA() {
        System.out.println("Calling the method A !");
    }
}

// And I have an another package :   

package com;
import bk.A;

public class B extends A {
    public void methodB() {
        System.out.println("Goi phuong thuc B !");
    }

    public static void main(String[] args) {
         A a = new B();
         a.methodA();

    }
}

How can I allow a to call methodA()?

+6  A: 

Cause methodA() is protected and it can be called within derived classes only. Change it to public if you want to call it like this

Arseny
@Daniel: in a static method...?
Pontus Gagge
Accroding the Sun's tutorials :The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.If so,I am wrong or they are wrong ? here.The Class B extends A,but B in an another package.
OOP
@OOP you can call methodA() in methodB() without creating an instance.
Arseny
@OOP: You answered your own question with that statement :)
0A0D
A: 

Protected methods can only be called from within the class itself, or from derived classes.

The a variable is declared as a variable of type A. Class A itself has no publicly available methodA, so you cannot call it.

Yes, you assign a new B instance to the a variable and the a.methodA() statement is inside the derived B class, but the compiler only sees that a is of type A. It could be any other subclass of A as well, in which case you still wouldn't have access to methodA.

You'll have to tell the compiler that the a variable is actually of type B. Then you will be able to call methodA, because you're calling it from within class B.

B a = new B();
Niels van der Rest
A: 

You are trying to access methodA() like it is public. Declaring simply methodA() in the B class is fine, but you cannot do a.methodA().

Conversely if it wasn't a method and simply protected int a; you could do

a = 1; in class B

but

A a = new A();
a.a = 1;

is not legal

A protected method is visible to inheriting classes, even not part of the same package. A package scope (default) method is not. That is the only difference between protected and package scope.

The theory is that someone extending your class with protected access knows more about what they are doing than someone who is merely using it with public access. They also need more access to your class’s inner workings. Other than that, protected behaves like default package access.

0A0D