In java can an abstract method be anything other than public?
In java can an abstract method be anything other than public? Are abstract methods implicitly public or 开发者_StackOverflow社区are they package if you don't specify? (regular methods are implicitly package right?) are there any visibility modifiers that an abstract method can't have? (private strikes me as problematic)
abstract
methods have the same visibility rules as normal methods, except that they cannot be private
.
Why don't you just test it?
abstract class A {
private abstract void pri ();
protected abstract void pro ();
abstract void pa ();
public abstract void pu ();
}
javac A.java
A.java:2: illegal combination of modifiers: abstract and private
private abstract void pri ();
^
1 error
a) Yes, a private abstract method is useless, and makes the whole class useless.
abstract class B {
// private abstract void pri ();
protected abstract void pro ();
abstract void pa ();
public abstract void pu ();
}
public class A extends B {
protected void pro () {} ;
void pa () {} ;
public void pu () {} ;
}
The other access modifying keywords are all accepted.
Default and Protected level visibility are also usable.
Default accessibility for abstract method can also be problematic if subclass is in different package, As members with Default accessibility can only be accessed by classes in same package.
And if you can not access inherited abstract class, you will not be able to override it. Example as below.
package PackA;
abstract public class SupClassA
{
protected abstract void pro();
abstract void pa();
}
package PackB;
import PackA.*;
class SubclassB extends SupClassA
{
protected void pro()
{
System.out.print("This is implementation of Pro method");
}
void pa()
{
System.out.print("This is implementation of Pa method");
}
}
When compiled, compiler complains that it can not override method pa, even though implementation is provided.(Works when pa() method is declared as protected in both classes)
E:\VrushProgs>javac -d . PackA\SupClassA.java
E:\VrushProgs>javac -d . PackB\SubClassB.java
PackB\SubClassB.java:3: error: SubclassB is not abstract and does not
override abstract method pa() in SupClassA
class SubclassB extends SupClassA
^
1 error
Only public
& abstract
are permitted in combination to method.
Example:
public abstract void sum();
We use abstract keyword on method because Abstract methods do not specify a body.
精彩评论