I have a question about OOP .I Need Your help !
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.met开发者_开发技巧hodA();
}
}
How can I allow a
to call methodA()
?
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
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();
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.
精彩评论