I am trying to use a protected static method in the Lucene information retrieval api. My understanding of static is that they are accessed from the class definition and my understanding of the protected keyword is that they can only be accessed from instances of that class or the subclass. So how exactly do you access a static protected method? Is my understanding mistaken? I am trying to call a protected static method from a library in an imported jar. How would I do that?
In this case I am calling the loadStopwordSet from StopwordAnalyzerBase
Why can't you call this method by referring to it as StopwordAnalyzerBase.loadStopwordSet(params) ?
Consider this example (which compiles and works on my machine):
package p1;
public class C1 {
protected void nonStatic() {}
protected static void isStatic() {}
}
----
package p2;
import p1.C1;
public class C2 extends C1 {
public void someMethod() {
super.nonStatic();
C1.isStatic(); // or even C2.isStatic()
}
}
Getting back to your original question, I can see that this method is called from within ArabicAnalyzer:78 (Lucene version 4.9.0, package org.apache.lucene.analysis.ar) as well as many others.
The "Base" part of the class name should give you a hint: this is meant to be called from a subclass of StopwordAnalyzerBase
It is static because it need not be an instance method (it is self-contained and does not alter the state of the object that calls it). Looking at the API doesn't tell me why it would be protected, though - apart from following the minimum privilege principle, I suppose
Related
I'm studying Swing in Java at first.
above thing is correct and another thing is incorrect code.
Correct
public class Example extends JFrame{
public Example() {
}
Incorrect
public class Example extends JFrame{
public Othor() {
}
Despite it's not Constructor, why function name should be same with class name?
I am not sure what you mean with "Despite it's not Constructor" - in the first snippet, public Example() is a constructor, means it will be executed when the object is created with new Example(). In the second snippet, public Othor() would be a normal method of the class, even though it is missing the return type, so this does not compile (this is probably the error message you get, something like Return type is missing).
The correct code for the second snipped would be something like
public class Example extends JFrame{
public void othor() {
}
}
(note that methods usually start with a non-capital letter). In this case, a default constructor would implicitly be created, but void othor() is a normal method of the class.
Also note that this is just normal Java behaviour, and completely independant of Swing or any other toolkit or framework.
See also Purpose of a constructor in Java?
class MyClass
{
public static final int num=90;
}
Why am I allowed to create a public member in a non-public class?
Is there another way of accessing this member that I do not know of (other than through the class name)?
Since your question was about members, I will address both fields and methods (non-static; Anthony Accioly's answer touches on another good use case, which also includes static fields).
While in many situations this is just an ambiguous consequence of the language's grammar (in particular: public fields in non-public classes, as in your example snippet), there are very good reasons for needing to be able to use public methods in non-public classes.
Expanding on Mik378's answer, consider, e.g., the following (contrived example):
import ...;
class BleebleAscendingComparator implements Comparator<Bleeble> {
#Override public int compare (Bleeble o1, Bleeble o2) { ... }
}
class BleebleDescendingComparator implements Comparator<Bleeble> {
#Override public int compare (Bleeble o1, Bleeble o2) { ... }
}
public class BleebleView {
public enum SortMode { ASC, DESC };
public Comparator<Bleeble> getDisplayOrderComparator (SortMode mode) {
if (mode == SortMode.ASC)
return new BleebleAscendingComparator();
else
return new BleebleDescendingComparator();
}
}
You cannot instantiate one of those Comparator implementations directly outside of that context, but they must override public methods of Comparator, and their functionality is accessible via a Comparator interface.
This same reasoning applies to, e.g., private or protected inner classes. If you were not able to declare methods public, you would have no way of overriding public methods of interfaces that they inherit or classes that they extends.
Practical Examples:
You use this every time you override a public method in an anonymous inner class (e.g. every time you override public void actionPerformed in an anonymous ActionListener).
Consider any non-public class that you would like to store in a HashMap. You would override the public equals() and hashCode() in that non-public class, and the implementation of HashMap can access them regardless of the fact that the class is non-public.
The often overridden public toString() is another common example of a public member of a potentially non-public class.
A more complex example is the use of java.sql.Driver in java.sql.DriverManager (in general, factory-type designs make heavy use of this concept) -- an SQL driver implementation may not make implementation classes public (e.g. the Oracle driver produces non-public Connection objects).
Many more... if you keep an eye out for examples of this, you'll be surprised how common it really is!
Don't forget that classes with default access can be subclassed by public classes in the same package.
package package1;
class MyDefaultClass {
public static final int MY_CONSTANT = 0xCAFEBABE;
}
public class PublicExporter extends MyDefaultClass {
}
Now the public class acts as a bridge, and you are able to consume MyDefaultClass public members from other packages.
package package2;
import package1.PublicExporter;
public class Consumer {
public static void main(String[] args) {
System.out.printf("%x\n", PublicExporter.MY_CONSTANT);
}
}
Consumers can even import static members:
import static package1.PublicExporter.MY_CONSTANT;
public class Consumer {
public static void main(String[] args) {
System.out.printf("%x\n", MY_CONSTANT);
}
}
When a public method belonging to an enclosing class A returns a reference (public supertype reference, like an interface) to its inner class B having default scope, external client (outside A's package) can only call B's methods but can't CREATE themselves fresh instances of B.
If the B's methods weren't public, external client couldn't reach them, and worse: would cause a compilation error since not well implementing its interface.
This modeling could be useful in a certain context, to improve code design.
When you declare a variable public it essentially becomes exactly that ; it's able to be seen throughout your entire program, without any special getters/setters. The class does not necessarily need to be public in order for its members to be public also.
Remember, in Java you can only have 1 public class per compilation unit( .java file), and that public class needs to have the same name as the compilation unit. Other than that, it doesn't "own" ownership of the keyword public.
The fact that you declared num as public and static allows you to say System.out.println(MyClass.num). The public attribute allows you to get the num variable directly. Thus, you do not have to create a method to return num for you. Because it is public, you can also say
MyClass mc = new MyClass();
System.out.println(mc.num);
However, since you also added the static declaration, you should only access it via the class name, i.e MyClass.num
Point to take home: public variables can exist in any type of class, and they allow you to access them without the need for getters and setters. Public classes, however, are not the only classes that can own public variables.
Can anybody explain me why do we need "protected" word?
If I understand correctly,
default access: available in classes within the same package.
protected access: default access in same package + available to inherited classes
(sub-classes) in any package. Basically, we get the same
default access in same package.
So when should I use it? Just for the style of your code? To mark it that you are going to work with it from perspective of inheritance?
Thank you.
package firstPack;
public class First {
protected int a;
protected void Chat(){
System.out.println("Here I am");
}
}
package secondPack;
import firstPack.First;
public class Second extends First{
public static void main(String [] args){
First f=new First();
// f.Chat();
// System.out.println(f.a);
}
}
I used this code to test it. It didn't work.
protected means visible to all sub-classes, not just those in the same package.
Problem with your test code is that you ware trying to access protected members of First class instance and via First class reference. Notice that since Second class is not in the same package as First one it doesn't have access to protected fields of any instance of base class, but have access to its own fields inherited from First class (which includes protected ones). So something like
First f = new First();
f.chat();//chat is protected in base class.
will not compile in Second class, but something like
public void test() {
a = 1; // have access to inherited protected field or
chat(); // methods of base class
}
public static void main(String[] args) {
Second f = new Second();
f.chat();
System.out.println(f.a);
}
is OK since Second class have access to its inherited members.
Notice that code in main method works only because it is placed inside Second class since only derived classes or classes in the same package as First have access to its protected members. So if this code will be placed inside other class like
class Test{
public static void main(String[] args) {
Second f = new Second();
f.chat();
System.out.println(f.a);
}
}
it will not compile (no access to protected members because Test doesn't extend or is not in same package as First).
The protected modifier: Accessed by other classes in the same package or any
subclasses of the class in which they are referred (i.e. same package or different package).
Reference
I know that an interface must be public. However, I don't want that.
I want my implemented methods to only be accessible from their own package, so I want my implemented methods to be protected.
The problem is I can't make the interface or the implemented methods protected.
What is a work around? Is there a design pattern that pertains to this problem?
From the Java guide, an abstract class wouldn't do the job either.
read this.
"The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface."
Is that what you want?
You class can use package protection and still implement an interface:
class Foo implements Runnable
{
public void run()
{
}
}
If you want some methods to be protected / package and others not, it sounds like your classes have more than one responsibility, and should be split into multiple.
Edit after reading comments to this and other responses:
If your are somehow thinking that the visibility of a method affects the ability to invoke that method, think again. Without going to extremes, you cannot prevent someone from using reflection to identify your class' methods and invoke them. However, this is a non-issue: unless someone is trying to crack your code, they're not going to invoke random methods.
Instead, think of private / protected methods as defining a contract for subclasses, and use interfaces to define the contract with the outside world.
Oh, and to the person who decided my example should use K&R bracing: if it's specified in the Terms of Service, sure. Otherwise, can't you find anything better to do with your time?
When I have butted up against this I use a package accessible inner or nested class to implement the interface, pushing the implemented method out of the public class.
Usually it's because I have a class with a specific public API which must implement something else to get it's job done (quite often because the something else was a callback disguised as an interface <grin>) - this happens a lot with things like Comparable. I don't want the public API polluted with the (forced public) interface implementation.
Hope this helps.
Also, if you truly want the methods accessed only by the package, you don't want the protected scope specifier, you want the default (omitted) scope specifier. Using protected will, of course, allow subclasses to see the methods.
BTW, I think that the reason interface methods are inferred to be public is because it is very much the exception to have an interface which is only implemented by classes in the same package; they are very much most often invoked by something in another package, which means they need to be public.
This question is based on a wrong statement:
I know that an interface must be public
Not really, you can have interfaces with default access modifier.
The problem is I can't make the interface or the implemented methods protected
Here it is:
C:\oreyes\cosas\java\interfaces>type a\*.java
a\Inter.java
package a;
interface Inter {
public void face();
}
a\Face.java
package a;
class Face implements Inter {
public void face() {
System.out.println( "face" );
}
}
C:\oreyes\cosas\java\interfaces>type b\*.java
b\Test.java
package b;
import a.Inter;
import a.Face;
public class Test {
public static void main( String [] args ) {
Inter inter = new Face();
inter.face();
}
}
C:\oreyes\cosas\java\interfaces>javac -d . a\*.java b\Test.java
b\Test.java:2: a.Inter is not public in a; cannot be accessed from outside package
import a.Inter;
^
b\Test.java:3: a.Face is not public in a; cannot be accessed from outside package
import a.Face;
^
b\Test.java:7: cannot find symbol
symbol : class Inter
location: class b.Test
Inter inter = new Face();
^
b\Test.java:7: cannot find symbol
symbol : class Face
location: class b.Test
Inter inter = new Face();
^
4 errors
C:\oreyes\cosas\java\interfaces>
Hence, achieving what you wanted, prevent interface and class usage outside of the package.
Here's how it could be done using abstract classes.
The only inconvenient is that it makes you "subclass".
As per the java guide, you should follow that advice "most" of the times, but I think in this situation it will be ok.
public abstract class Ab {
protected abstract void method();
abstract void otherMethod();
public static void main( String [] args ) {
Ab a = new AbImpl();
a.method();
a.otherMethod();
}
}
class AbImpl extends Ab {
protected void method(){
System.out.println( "method invoked from: " + this.getClass().getName() );
}
void otherMethod(){
System.out.println("This time \"default\" access from: " + this.getClass().getName() );
}
}
Here's another solution, inspired by the C++ Pimpl idiom.
If you want to implement an interface, but don't want that implementation to be public, you can create a composed object of an anonymous inner class that implements the interface.
Here's an example. Let's say you have this interface:
public interface Iface {
public void doSomething();
}
You create an object of the Iface type, and put your implementation in there:
public class IfaceUser {
private int someValue;
// Here's our implementor
private Iface impl = new Iface() {
public void doSomething() {
someValue++;
}
};
}
Whenever you need to invoke doSomething(), you invoke it on your composed impl object.
I just came across this trying to build a protected method with the intention of it only being used in a test case. I wanted to delete test data that I had stuffed into a DB table. In any case I was inspired by #Karl Giesing's post. Unfortunately it did not work. I did figure a way to make it work using a protected inner class.
The interface:
package foo;
interface SomeProtectedFoo {
int doSomeFoo();
}
Then the inner class defined as protected in public class:
package foo;
public class MyFoo implements SomePublicFoo {
// public stuff
protected class ProtectedFoo implements SomeProtectedFoo {
public int doSomeFoo() { ... }
}
protected ProtectedFoo pFoo;
protected ProtectedFoo gimmeFoo() {
return new ProtectedFoo();
}
}
You can then access the protected method only from other classes in the same package, as my test code was as show:
package foo;
public class FooTest {
MyFoo myFoo = new MyFoo();
void doProtectedFoo() {
myFoo.pFoo = myFoo.gimmeFoo();
myFoo.pFoo.doSomeFoo();
}
}
A little late for the original poster, but hey, I just found it. :D
You can go with encapsulation instead of inheritance.
That is, create your class (which won't inherit anything) and in it, have an instance of the object you want to extend.
Then you can expose only what you want.
The obvious disadvantage of this is that you must explicitly pass-through methods for everything you want exposed. And it won't be a subclass...
I would just create an abstract class. There is no harm in it.
With an interface you want to define methods that can be exposed by a variety of implementing classes.
Having an interface with protected methods just wouldn't serve that purpose.
I am guessing your problem can be solved by redesigning your class hierarchy.
One way to get around this is (depending on the situation) to just make an anonymous inner class that implements the interface that has protected or private scope. For example:
public class Foo {
interface Callback {
void hiddenMethod();
}
public Foo(Callback callback) {
}
}
Then in the user of Foo:
public class Bar {
private Foo.Callback callback = new Foo.Callback() {
#Override public void hiddenMethod() { ... }
};
private Foo foo = new Foo(callback);
}
This saves you from having the following:
public class Bar implements Foo.Callback {
private Foo foo = new Foo(this);
// uh-oh! the method is public!
#Override public void hiddenMethod() { ... }
}
I think u can use it now with Java 9 release. From the openJdk notes for Java 9,
Support for private methods in interfaces was briefly in consideration
for inclusion in Java SE 8 as part of the effort to add support for
Lambda Expressions, but was withdrawn to enable better focus on higher
priority tasks for Java SE 8. It is now proposed that support for
private interface methods be undertaken thereby enabling non abstract
methods of an interface to share code between them.
refer https://bugs.openjdk.java.net/browse/JDK-8071453
Say there's the following base class:
package bg.svetlin.ui.controls;
public abstract class Control {
protected int getHeight() {
//..
}
//...
}
Also, in the same package, there's a class that inherits:
package bg.svetlin.ui.controls;
public abstract class LayoutControl extends Control {
public abstract void addControl(Control control);
//...
}
Then, there's a third class in another package:
package bg.svetlin.ui.controls.screen;
public abstract class Screen extends LayoutControl {
//...
}
And, finally, there's the implementation class, again in a different package:
package bg.svetlin.ui.controls.screen.list;
public class List extends Screen {
private final Vector controls = new Vector();
public void addControl(Control control) {
height += control.getHeight();
controls.addElement(control);
}
}
Even though List inherits from Control, and the getHeight() is protected, there's the following error:
getHeight() has protected access in bg.svetlin.ui.controls.Control
I've checked that my imports are right. I'm using NetBeans.
Any idea what's wrong? I thought protected fields and methods are visible to the children even if the latter are in a different package.
Thanks!
I thought protected fields and methods are
visible to the children even if the latter are in a different package.
That's correct. The class itself has an access to the inherited protected members. But, what you're trying to do it to call the getHeight method on some Control reference. You're allowed to call it only on this instance!
For a better understanding, let me quote Kathy Sierra's SCJP Preparation Guide:
But what does it mean for a subclass-outside-the-package to have
access to a superclass (parent) member? It means the subclass inherits
the member. It does not, however, mean the
subclass-outside-the-package can access the member using a reference
to an instance of the superclass. In other words, protected =
inheritance. The subclass can see the protected member
only through inheritance.
You're right. Any protected member or method accessible from children class, but you want access to protected method of a parameter instance in addControl method. You can access only to protected method of List class (this.getHeight())