Structure java classes (best practice) - java

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{
}

Related

Java - Constraining method parameter in an interface to the implementing class

I have an interface that is implemented by other classes. But I need one of the parameters of one methods of the interface to be restricted to the class implementing the interface.
One option to achieve what I need would be parametrizing the interface.
public interface Profile<T> {
public void aggregate(T p);
}
public class SpecificProfile implements Profile<SpecificProfile> {
public void aggregate(SpecificProfile p) {
...
}
}
Is there a cleaner way to achieve it without using generics?
No, it's not possible to declare "one of the parameters of one methods of the interface to be restricted to the class implementing the interface" in Java.

import class in different directory

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; }
}
}

Why we can't create protected methods in JAVA interfaces? [duplicate]

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

How a class can extend with two different classes While one class is from a external library and other is built in

I am using SherlockActionBar library in my project.And my class is extending an abstract class SherlockActivity
public class AllAppsInfo extends SherlockActivity{}
In mean while i want to extend my AllAppsInfo with FragmentActivity as well.Which is not allowed due to negligence of multiple inheritance in java.
I have done some search, composition is the solution but how to use it in this Scenario? Neither i can make abstract Sherlock class a interface nor same be done with Fragment Activity class
.
Try Composition.
You can refer here too.
The funda is simple:
class A
{
void aMethod() {}
}
class B
{
void bMethod() {}
}
class C
{
void cMethod() {}
}
if you want to call aMethod() and bMethod() from cMethod(); you can do following way:
class C extends A // Inheritance
{
B aBObject = null; // Composition
void cMethod()
{
aMethod();
aBObject = new B();
aBObject.bMethod();
}
}
Yes, In Java we do not have multiple inheritance.
You have two options ahead of you.
use composite pattern. described here
Recreate your class hierarchy, by adding few more interfaces and base classes.
I have solved this issue by extending my class with SherlockFragmentActivity
public class AllAppsInfo extends SherlockFragmentActivity{}
Java has not full multiple inheritance, C++ has. You need workarounds to do it like composition

Avoid repeated imports in Java: Inherit imports?

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
}
}

Categories

Resources