Is there any security/access difference when making a package access
level abstract class's non-static methods public vs making them protected? Only classes
from within the same package that extend the abstract class can access the non-static
methods anyway right? So, does it matter whether those non-static methods are public or
protected since the abstract class itself places restrictions on who can extend
it?
abstract class MyClass
{
protected void myFunction(){
System.out.println("Only
child classes can print this");
}
}
abstract
class MyClass {
public void myFunction(){
System.out.println("Still, only child classes can print this");
}
}
Answer
The public abstract
will be accessible in the other package where as the
method
protected abstract method
can not be accessed. Check the
example below.
An abstract class with both
public and protected abstract
methods
package
package1;
public abstract class MyClass {
abstract
protected String method1();
abstract public String
method2();
}
Another
package which extends the class and implements the abstract
class.
package
package2;
import
package1.MyClass;
public class MyClassImpl extends
MyClass {
@Override
protected String method1() {
return
"protected method";
}
@Override
public
String method2() {
return "public method";
}
}
Main
class for accessing the abstract method.
package
package2;
import package1.MyClass;
public
class MainClass {
static MyClass myClass = new
MyClassImpl();
public static void main(String[] args) {
System.out.println(myClass.method1()); // This is compilation error.
System.out.println(myClass.method2());
}
}
No comments:
Post a Comment