Tuesday 5 December 2017

java - Public vs. Protected abstract class method





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
method
will be accessible in the other package where as the
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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...