The java compiler allows me write a Class definition inside an Interface . Are there any specific uses of this ?
interface ClassInterface {
void returnSomething();
int x = 10;
class SomeClass {
private int y;
private void classDoingSomething() {
}
}
}
Please explain .
The uses are the same that a class nested in another class: it allows scoping the class to the interface. You could imagine something like this:
public interface Switch {
public enum Status {
ON, OFF;
}
void doSwitch();
Status getStatus();
}
It avoids defining a top-level class named SwitchStatus (because Status could be a too generic name).
Yes Java allows you to define an inner class inside an interface One use I can think of is tightly binding a certain type (defined by the class) to an interface and perhaps limit access only to the interface methods. There's an example of such use on here
I use that pattern to embed multiple tiny concrete implementations that share a large amount of commonality. It's easier to manage 25 tiny extensions of the same abstract class within the same file. Using like in C# namespace enclosure.
/**
* Dao 道 = access/way/avenue
* Bao 包 = bundle/package/
*/
public interface DaoBao {
public abstract class <E extends BlessedEntity> BlessedDaoWager<E,T> {
private JdbcTemplate jtmpl;
public void setDatasource(Datasource ds) {
this.jtmpl = new JdbcTemplate(ds);
}
public E find(BlessedKey key) {
blah .. blah .. blah ...
}
public List<E> list(Date from, Date to) {
blah .. blah .. blah ...
}
public boolean remove(BlessedKey key) {
blah .. blah .. blah ...
}
public T getKey(E ent) {
return ent.getId();
}
}
public class BlessedEmployeeDao
extends BlessedDaoWager<BlessedEmployeeEntity, Long> {
public Long getKey(BlessedEmployeeEntity ent) {
return ent.getCucurucucu();
}
}
public class BlessedSalaryDao
extends BlessedDaoWager<BlessedSalaryEntity, BlessedEmployeeEntity> {
public BlessedEmployeeEntity getKey(BlessedSalaryEntity ent) {
return ent.getEmployeeId();
}
}
public class BlessedHoursDao
extends BlessedDaoWager<BlessedHoursEntity, BlessedEmployeeEntity> {
public BlessedEmployeeEntity getKey(BlessedSalaryEntity ent) {
return ent.getEID();
}
}
public class BlessedGooDao
extends BlessedDaoWager<BlessedGooEntity, String> {
public String getKey( ent) {
return ent.getName();
}
}
public class BlessedHowDao extends BlessedDaoWager<BlessedEntity, Long> {}
public class BlessedNowDao extends BlessedDaoWager<BlessedEntity, Date> {}
}
There are those who say, what if someone inadvertently implemented the interface. I would say those are inadvertent programmers looking for ways to prevent their inadvertent programming habits.
Related
I am working with the DAO pattern on Java, for the implementation I use a DAO interface that is implemented by a "ItemDAO" abstracted class witch then leads to classes like "ItemDAOTxt" and "ItemDAOXml". This same logic is used on classes like "OrderDAO" and "EmployeesDAO; I am working on a abstract class that will use a DAO in a particular way, "ClassA". So is there a way to make some different classes extends "ClassA" in a way that I can use any DAO I want?
public abstract class ClassA
{
private DAO<T> dao;
//...
}
maybe this:
interface Foo<T> {
T getValue();
}
abstract class Bar<T,U> implements Foo<T> {
Bar(T t,U u) {
this.t=t;
this.u=u;
}
#Override public T getValue() {
return t;
}
T t;
U u;
}
class Baz<T,U>extends Bar<T,U> {
Baz(T t,U u) {
super(t,u);
}
}
public class So56811426 {
public static void main(String[] args) {
Baz<Integer,Character> baz=new Baz<Integer,Character>(42,'x');
System.out.println(baz.getValue()+" "+baz.u);
}
}
I am confused about how to define classes and interfaces hierarchy for below scenario.
Below are the interfaces
public interface Save {
public void save(List<Object> pojoList);
public void save(String query);
}
public interface Update {
public void update(List<Object> pojoList, List<String> conditionList);
public void update(String query);
}
public interface Delete {
public void delete(String query);
}
And here are the classes :
Class DbOperations {
}
class SaveOperation extends DbOperations implements Save {
}
class UpdateOperation extends DbOperations implements Update {
}
So my concerns are:
I want call SaveOperation, DeleteOpration class methods using instance of DbOperations (base class)
can you tell me which class should be which interface?
any modification for above hierarchy??
Thanks in advance
What you get by having an interface implemented by multiple classes is that you can define a method that takes the interface as parameter and calls one of its methods, then the result of that call would depend on the actual type of that interface at runtime.
That said, I don't see any advantage in defining an interface DbOperation that doesn't define any method its classes will inherit.
If you have reasons to do so (it's possible, if the code you wrote is just a simplification of your scenario), from a semantical point of view I would find more meaningful having DbOperations as the root interface of the hierarchy, and Save, Update and Delete as abstract classes (or interfaces) between the actual classes and the root:
public interface DbOperation {
public String thisOperation();
}
public abstract class Save implements DbOperation {
public String thisOperation(){
return "Save";
}
public void save(List<Object> pojoList);
public void save(String query);
}
public abstract class Update implements DbOperation{
public String thisOperation(){
return "Update";
}
public void update(List<Object> pojoList, List<String> conditionList);
public void update(String query);
}
public abstract class Delete implements DbOperation {
public String thisOperation(){
return "Delete";
}
public void delete(String query);
}
class SaveOperation implements Save {
}
class UpdateOperation implements Update {
}
So regarding your concern,
I want call SaveOperation, DeleteOpration class methods using instance
of DbOperations (base class)
I think, it will go something like this:
DbOperations op = new SaveOperation(/*Params*/);
// Check type to cast
if(op instanceof Save)
{
// Cast to Save and call method
((Save)op).save(/*Params*/);
}
// For delete
if(op instanceof Delete)
{
// Cast to Save and call method
((Delete)op).delete(/*Params*/);
}
So, you don't need any modification.
Assume I have an interface with a class embedded in it (the purpose being that this interface must provide a 'type'. The interface has some methods using that 'type'. So, in file S.java, I have
public interface S {
public class SType
{
}
public abstract void f( SType a );
}
I want to implement this interface, and I try this, in file SS.java:
public final class SS implements S
{
public class SType extends java.util.HashSet<Integer>
{
}
public void f( SType a )
{
// ...
}
}
However, when I try to compile these files ("javac S.java SS.java"), I get the usual error message "SS is not abstract and does not override abstract method f(SType) in S" indicating that "f()" in the concrete class is not a proper implementation of "f()" in the interface. Why?
Try with:
public final class SS implements S{
public class SType extends java.util.HashSet<Integer>
{
}
public void f(S.SType a) {
// ..
}
}
EDIT:
Perhaps, you need this:
public interface S<SType> {
public void f( SType a );
}
public final class SS implements S<HashSet<Integer>> {
public void f(HashSet<Integer> a ){
// ...
}
}
I am way over thinking this: What I am trying to do is [hopefully not reinvent the wheel and] come up w/ a [Android] Java eventing mechanism that allows subclasses to pre-define an arbitrary set of "features" with getters and setters that fire individual callbacks.
I think I am fusioning some combination of Command, Visitor, Decorator, Facade and Observer patterns here, and confusing myself along the way.
I have been programming for well over 20 years, but I feel like a n00b on this fairly simple problem! :(
I have searched SO for the compiler error and read many of the results, but I still haven't found a solution that works for me.
(How to make a Java class that implements one interface with two generic types? seems to be the most relevant one that I have found, but I also want to generically get the values and fire events to callbacks when they are set).
First, let the below mostly valid code speak for itself...
interface IFeature
{
}
interface IFeatureCallbacks<T extends IFeature>
{
boolean onChanged(Feature<T> c);
}
public static class Feature<T extends IFeature>
{
private Set<IFeatureCallbacks<T>> listeners = new LinkedHashSet<>();
public void addListener(IFeatureCallbacks<T> listener)
{
listeners.add(listener);
}
public void removeListener(IFeatureCallbacks<T> listener)
{
listeners.remove(listener);
}
protected void onChanged()
{
for (IFeatureCallbacks<T> listener : listeners)
{
listener.onChanged(this);
}
}
}
//
interface IFeatureA
extends IFeature
{
int getA();
}
interface IFeatureACallbacks
extends IFeatureCallbacks<IFeatureA>
{
}
public static class FeatureA
extends Feature<IFeatureA>
implements IFeatureA
{
private int a;
public void setA(int value)
{
a = value;
onChanged();
}
#Override
public int getA()
{
return a;
}
}
//
interface IFeatureB
extends IFeature
{
boolean getB();
}
interface IFeatureBCallbacks
extends IFeatureCallbacks<IFeatureB>
{
}
public static class FeatureB
extends Feature<IFeatureB>
implements IFeatureB
{
private boolean b;
public void setB(boolean value)
{
b = value;
onChanged();
}
#Override
public boolean getB()
{
return b;
}
}
//
interface IDeviceWithFeatureA
extends IFeatureA
{
}
interface IDeviceWithFeatureACallbacks
extends IFeatureACallbacks
{
}
public static class DeviceWithFeatureA
extends Feature<IDeviceWithFeatureA>
implements IDeviceWithFeatureA
{
FeatureA a = new FeatureA();
public void addListener(IDeviceWithFeatureACallbacks listener)
{
a.addListener(listener);
}
public void setA(int value)
{
a.setA(value);
}
#Override
public int getA()
{
return a.getA();
}
}
//
interface IDeviceWithFeatureB
extends IFeatureB
{
}
interface IDeviceWithFeatureBCallbacks
extends IFeatureBCallbacks
{
}
public static class DeviceWithFeatureAB
extends Feature<IDeviceWithFeatureB>
implements IDeviceWithFeatureB
{
FeatureB b = new FeatureB();
public void addListener(IDeviceWithFeatureBCallbacks listener)
{
b.addListener(listener);
}
public void setB(boolean value)
{
b.setB(value);
}
#Override
public boolean getB()
{
return b.getB();
}
}
The above code seems to work fine, albeit something about it smells a bit off.
The problem is when I try to do this:
interface IDeviceWithFeatureAAndFeatureB
extends IFeatureA, IFeatureB
{
}
/*
Compiler error:
'IFeatureCallbacks' cannot be inherited with different type arguments 'IFeatureA' and 'IFeatureB'
*/
interface IDeviceWithFeatureAAndFeatureBCallbacks
extends IFeatureACallbacks, IFeatureBCallbacks
{
}
public static class DeviceWithFeatureAB
extends Feature<IDeviceWithFeatureAAndFeatureB>
implements IDeviceWithFeatureAAndFeatureB
{
FeatureA a = new FeatureA();
FeatureB b = new FeatureB();
public void addListener(IDeviceWithFeatureAAndFeatureBCallbacks listener)
{
a.addListener(listener);
b.addListener(listener);
}
public void setA(int value)
{
a.setA(value);
}
#Override
public int getA()
{
return a.getA();
}
public void setB(boolean value)
{
b.setB(value);
}
#Override
public boolean getB()
{
return b.getB();
}
}
I am less interested in trying to figure out how to make what I am trying to do compilable, and I am more interested in what about my abuse of a pattern is way off base so that I can re-write it to be both simpler and compile.
You are abusing the basic "pattern" of OOP -- inheritance. The adage is that "favor composition over inheritance". Think in terms of "contains", instead of "is-a".
Take Zoo for example. A zoo is just a bunch of animals, right? So naturally, we may want to declare Zoo as subtype of Set<Animal>. Perhaps even have class Zoo extends HashSet<Animal>.
However, that is likely a wrong design. A zoo is actually a lot of things. It contains a set of animals, sure; but it also contains a set of people (as workers, not exhibits (although...) ). So it's better to
class Zoo
Set<Animal> animals(){ ... }
Set<Person> workers(){ ... }
Anywhere we need to treat a zoo as a set of animals, just use zoo.animals(); think of it as a type cast, or projection. We don't need inheritance here.
In your design, you have too many types; what's worse, too many type relationships. It seems that you simply need one generic class that reads/writes value of T, and contains listeners of T
class Feature<T>
T value;
// getter
// setter
Set<ChangeListener<T>> listeners;
interface ChangeListener<T>
void onChange(T oldValue, T newValue)
A device contains a bunch of features
class SomeDevice
Feature<Integer> featureA = new Feature<>();
Feature<Boolean> featureB = new Feature<>();
That's it. You can operate on feature A of the device by operating on itsfeatureA.
Im trying to make a small DSL in Java that I can use to populate testdata in a database. The language I would like to use is as follows.
createRowInTableA().
createRowInTableB().
createRowInTableA().
createRowInTableB().
createRowInTableC().
end();
The order the tables are created is important, for example tableB depends on tableA and tableC depends on tableA and tableB. Therefore I want to make it so that the option to create tableB only is available directly after tableA is created etc. I have started to create the interfaces describing the DSL but I don't know how I should actually implement the interfaces inorder to make the type of nested behavior I'm looking for. This is what the interfaces looks like.
public interface End {
public void sendTestData();
}
public interface TableA extends End {
public Builder createRowInTableA();
}
public interface TableB extends TableA {
public Builder createRowInTableB();
}
public interface TableC extends TableB {
public Builder createRowInTableC();
}
However when I start implementing this language using builder pattern to create a fluent API the hierarchy I want goes away.
public class DBBuilder implements TableC {
static class Builder {
public Builder createRowInTableA(){...}
public Builder createRowInTableB(){...}
public Builder createRowInTableC(){...}
}
}
You can use a set of interfaces and class adapters:
public interface canCreateTableAIf{
public DBBuilderB createRowInTableA()
}
public interface canCreateTableBIf{
public DBBuilderC createRowInTableB()
}
public interface canCreateTableCIf{
public DBBuilderD createRowInTableC()
}
public class canCreateTableA implements canCreateTableAIf (){
public DBBuilderB createRowInTableA(){
...
}
}
public class canCreateTableB implements canCreateTableBIf (){
public DBBuilderC createRowInTableB(){
...
}
}
public class DBBuilderRoot extends canCreateTableA {
}
public class DBBuilderB extends canCreateTableB {
}
public class DBBuilderBCD extends canCreateTableB,canCreateTablec,canCreateTableD {
}
This is not so complicated. But I would check if there is a better way than using fluent Builders. Java 8 for example offers closures. Hier is my suggestion. I've not compiled and tested it. The idea should work but there might be syntax errors.
public class ABuilder
{
private BBuilder subBuilder;
public ABuilder()
{
subBuilder = new BBuilder(this);
}
public BBuilder createRowForA()
{
// your code
return this.subBuilder;
}
public void end()
{
// send test data
}
}
x
public class BBuilder
{
private ABuilder parentBuilder;
private CBuilder subBuilder;
public BBuilder( ABuilder parentBuilder )
{
this.parentBuilder = parentBuilder;
this.subBuilder = new CBuilder(this);
}
public CBuilder createRowForB()
{
// your code
return this.subBuilder;
}
public ABuilder end()
{
return this.parentBuilder;
}
}
x
public class CBuilder
{
private BBuilder parentBuilder;
public CBuilder( BBuilder parentBuilder )
{
this.parentBuilder = parentBuilder;
}
public CBuilder createRowForC()
{
// your code
// I Assume you want to be able to write more than 1 C-row
return this;
}
public BBuilder end()
{
return this.parentBuilder;
}
}
Then you can do:
(new ABuilder())
.createRowForA()
.createRowForB()
.createRowForC()
.end()
.end()
.end();
(new ABuilder())
.createRowForA()
.createRowForB()
.end()
.createRowForB()
.createRowForC()
.end()
.end()
.end();
I'm sure you see more exmples. ;-)