Is there a way to "inherit" imports?
Example:
Common enum:
public enum Constant{ ONE, TWO, THREE }
Base class using this enum:
public class Base {
protected void register(Constant c, String t) {
...
}
}
Sub class needing an import to use the enum constants convenient (without enum name):
import static Constant.*; // want to avoid this line!
public Sub extends Base {
public Sub() {
register(TWO, "blabla"); // without import: Constant.TWO
}
}
and another class with same import ...
import static Constant.*; // want to avoid this line!
public AnotherSub extends Base {
...
}
I could use classic static final constants but maybe there is a way to use a common enum with the same convenience.
imports are just an aid to the compiler to find classes. They are active for a single source file and have no relation whatsoever to Java's OOP mechanisms.
So, no, you cannot “inherit” imports
If you're using Eclipse, use "Organize Imports" (Ctrl+Shift+O) to let the IDE do the imports for you (or use code completion (Ctrl+Space)
No, you can't inherit an import. If you want to reference a type within a class file without using the fully-qualified name, you have to import it explicitly.
But in your example it would be easy enough to say
public Sub extends Base {
public Sub() {
register(Constant.TWO, "blabla"); // without import: Constant.TWO
}
}
Related
I have written some Java classes to import the content of Excel file.
The content of the excel has mainly the following data types: static, dynamic and static dynamic together.
The question is what is the best structure to write the importer classes. I need methods to import dynamic, static and dynamic-static content
My idea is the following:
//Class to import dynamic content
abstract class DynamicImporter{
void importDynamicExcel(){
}
//class to import static content
abstract class StaticImporter{
void importStaticExcel(){
}
Now the problem is that I have excel which have bouth dynamic and static content. It is not possible
to do something like this
abstract class DynamicStaticImporter extends StaticImporter, StaticImporter{
}
Any Idea what could be alternative to solve such kind of problems?
Use an ExcelImporter interface, an AbstractExcelImporter for shared code and the three implementations you need.
You will need one abstract class with shared implementation. There is no need for 3 abstract classes. Alternatively you can use builder pattern for composition
abstract class AbstractExcelImporter{
void importExcel(){
//implementation
}
}
//Class to import dynamic content
class DynamicImporter extends AbstractExcelImporter{
void importDynamicExcel(){
importExcel();
//type spesific implementation or overridde importExcel method
}
}
An alternative to implementing dispatch on multiple inheritance is to flatten the hierarchy into a single class, and give it a single method that takes a descriptor of what kind of import to do (static, dynamic, etc.) as its parameter:
enum ImportType {
STATIC
, DYNAMIC
, STATIC_DYNAMIC
}
class Importer {
void importExcel(ImportType impType) {
...
}
}
In turn ImportType enumeration could be enhanced with properties and methods directing the process of importing Excel data into your application.
You can't inherit of two disctinct classes but you can implements as many interface as you want. You can do something like that :
interface DynamicImporter{
void importDynamicExcel(){
}
}
interface StaticImporter{
void importStaticExcel(){
}
}
And then, your class becomes :
abstract class DynamicStaticImporter implements StaticImporter, StaticImporter{
}
If you need some common code, you can also have
abstract class AbstractImporter {
someMethod() {
}
}
In that case, your class will become :
abstract class DynamicStaticImporter extends AbstractImporter implements StaticImporter, StaticImporter{
}
Is it legal to have 2 classes in the same package, where one class is a subclass of the other, where the subclass is public while the super class is package private?
eg:
package test;
class SuperClass {
public void f(){}
}
package test;
public class SubClass extends SuperClass {
}
Is it legal?
If so, are there any technical reasons (not opinion) why it should not be used?
Is this widely understood behavior?
Is this recommended? (opinion)
My testing shows that JavaDoc renders the docs for the sub class as if the super class did not exist. No mention of a super class. Public methods declared and implemented in the super class are shown as though they were declared in the sub class.
Java reflection API shows similar behavior: public methods declared and implemented in the super class return the sub class when .getDeclaringClass() is called on the Method. However, subclass.getSuperclass() does return the correct super class.
Additional classes and output:
package test;
public class InstanceOfChecker {
public static boolean isInstanceOfSuperClass(Object o){
return (o instanceof SuperClass);
}
}
package otherpackage;
public class Test {
public static void main(String[] args) throws Exception {
System.out.println("f() declaring class: "
+ SubClass.class.getMethod("f").getDeclaringClass().getName());
System.out.println("super class: "
+ SubClass.class.getSuperclass().getName());
System.out.println("InstanceOfChecker returns: "
+ InstanceOfChecker.isInstanceOfSuperClass(new SubClass()));
}
}
Output:
f() declaring class: test.SubClass
super class: test.SuperClass
InstanceChecker returns: true
Is it legal?
Yes
If so, are there any technical reasons (not opinion) why it should not be used?
No
Is this widely understood behavior?
I haven't seen it often but you can find it a couple of times within the JVM (but I don't remember right now, where I've seen this)
Is this recommended? (opinion)
I'm not aware that I have ever seen a recommendation or discouragement of this technique.
Concerning why you want to do this. You might want to create a library with public classes that share a lot of code. So you create an abstract class containing this code that you don't want to expose to make sure that you can do changes to this class without breaking code "out there". protected can't prevent that so you make the abstract class package visible. It forces you to put all subclasses into the same package but that's not a real problem in general.
Actually, I am trying to finish this practice in "Think in Java" for self-learning purpose --
Exercise 6: (2) Create an interface with at least one method, in its own package. Create a
class in a separate package. Add a protected inner class that implements the interface. In a
third package, inherit from your class and, inside a method, return an object of the
protected inner class, upcasting to the interface during the return.
so I created a class named IgetResult.java under directory "a" which has a IIGetResult Interface.
interface IIGetResult {
String getResult();
}
public class IgetResult {
}
then I create another class in another directory -- directory b
import a.IgetResult.IIGetResult;
public class PracticeClass {
protected class inner implements IIGetResult {
#Override
String getResult(){ return "result";}
}
public static void main(String[] args) {
System.out.println("practice start");
}
}
In the final step, I compile the two java classes with command:
# javac a/.java b/.java
and get the following error:
./a/IgetResult.java:1: duplicate class: IIGetResult
interface IIGetResult {
^
./a/IgetResult.java:4: duplicate class: IgetResult
public class IgetResult {
^
b/PracticeClass.java:1: cannot access a.IgetResult
bad class file: ./a/IgetResult.java
file does not contain class a.IgetResult
Please remove or make sure it appears in the correct subdirectory of the classpath.
import a.IgetResult.IIGetResult;
^
Please teach me go through this practice, thanks in advance.
As per the quote:
Create an interface with at least one method, in its own package.
So we create IGetResult.java file in folder a:
package a;
public interface IGetResult {
String getResult();
}
Create a class in a separate package. Add a protected inner class that implements the interface.
Now we create a class in a separate package (folder), with inner class which implements the interface:
package b;
import a.IGetResult;
public class InnterTest {
protected class GetResultImpl implements IGetResult {
#Override
String getResult() { return "result"; }
}
}
In a third package, inherit from your class and, inside a method, return an object of the protected inner class, upcasting to the interface during the return
So now we create a sub-class of InnerTest class in third separate package:
package c;
import a.IGetResult;
import b.InnterTest;
public class InnerTestSubclass extends InnerTest {
public IGetResult getResultClass() {
//Up-casting happens automatically since GetResultImpl is sub-class of IGetResult
return new GetResultImpl();
}
}
I typed it by hand, but you should get the idea. Hope that helps.
I can see the following issues:
You are missing the 'package <a/b/c>' declaration in your classes.
Your a.IIGetResult interface should be public, otherwise it won't be visible in the 'b' package.
The Java convention is for class name to start with an upper case, thus your inner class insided PracticeClass should be named 'Inner' instead.
Your inner class should have a public constructor, so that the later can be invoked from a class extending PracticeClass defined in another package.
The overriden inner.getResult() method should be public (but out-of-topic).
Your class IGetResult should be defined in a third package (c?) and should extends PracticeClass (though I must admit your instructions are a little bit confusing to me).
Aplly the above points along with #dimoniy's answer and you should be OK.
Your class needs to be inside of your interface. This needs to be in a file called IIGetResult.java
interface IIGetResult {
String getResult();
public class IgetResult implements IIGetResult{
#Override
String getResult() { return null; }
}
}
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.
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