Implementing the interface and joining the interface methods with instance variables - java

public interface Usable {
public boolean isUsed();
public void setAsUsed();
public void setAsNotUsed();
}
My question is:
The Book class has to implement the Usable interface and join the interface methods with status instance variable either to set the status of the as used or to set the status of the as not used or to return the current value of used instance variable.
I dont really understand how exactly to do what the question is asking.

Well for a start you will need
public class Book implements Usable {
and then because you have done this you will need to implement these methods which hint to the need for a boolean field called used
private boolean used;
public boolean isUsed() {
return used;
}
and hence
public void setAsUsed(used = true);
public void setAsNotUsed(used = false);

You have to create a class that implements Usable by defining the methods (in your case getters and setters) that are declared there:
public class Book implements Usable {
// Initialization
private boolean used = false;
// Getter
public boolean isUsed() {
return this.used;
}
// Setters
public void setAsUsed() {
this.used = true;
}
public void setAsNotUsed() {
this.used = false;
}
}

I assume this is your book class:
public class Book {
private boolean used;
// other things
}
To implement the interface, first you need to
public class Book implements Usable {
//...
Then, implement the methods one by one. We can guess what each one does by looking at the name and signature. isUsed returns a boolean so it probably should return whether the book is used. Let's implement this:
public boolean isUsed() {
return used;
}
setAsUsed, well, set the book as used:
public void setAsUsed() {
used = true;
}
And setAsNotUsed does what it says on the lid as well:
public void setAsNotUsed() {
used = false;
}

Related

Is there someway to restrict the access to a member of an object only to the object that owns it by composition?

I really feel like there must be a way around this.
Imagine I have a large number of objects as components of an owner class. I want to offer easy access to the clients of this owner class to its members, so I make all those objects public. Each of those objects also have all their members public. But one member of the components should not be accessible to the clients of their owner, only by their owner itself:
public class ComponentObject
{
public int int_field;
public float float_field;
public Object object_field;
public Object public_method1()
{
//something;
}
public Object public_method2()
{
//something;
}
public Object restricted_to_owner_only()
{
//something;
}
}
//all clients of Owner should be able to access all the members of its components, except
//restricted_to_owner_only, which only Owner should be able to access
public class Owner
{
public ComponentObject component1;
public ComponentObject component2;
public ComponentObject component3;
//... lots of others
public ComponentObject component300;
}
Is there a way to achieve this? Note that any class from any package can own a ComponentObject, so using package level visibility at restricted_to_owner_only doesn't seem to be an option. ComponentObject is like a utility class, reusable in other applications.
Maybe there's an annotation that enforces that at compile time in some nice lib out there?
EDIT: I forgot to mention that ComponentObject is a parameterized type in real life, and each field in Owner is parameterized differently. I tried to abstract off the details so we could focus on the design problem itself, but I abstracted too much. I will post bellow something more similar to the real problem:
public class ComponentObject<T>
{
public int int_field;
public float float_field;
public T object_field;
//any method could return T or take T as an argument.
public T public_method1()
{
//something;
}
public Object public_method2()
{
//something;
}
public Object restricted_to_owner_only()
{
//something;
}
}
//all clients of Owner should be able to access all the members of its components, except
//restricted_to_owner_only, which only Owner should be able to access
public class Owner
{
public ComponentObject<String> component1;
public ComponentObject<File> component2;
public ComponentObject<Consumer<Boolean>> component3;
//... lots of others
public ComponentObject<Integer> component300;
}
EDIT 2 (Possibly a solution): Guys, inspired by Romeo and Juliet's love, I wrote this solution, can you spot any faults with it? Or would it work as I intended?
//add this class
public class OwnershipToken
{
private static int id_gen = 0;
public final int id = id_gen++;
#Override
public boolean equals(Object obj)
{
return (obj instanceof OwnershipToken) && ((OwnershipToken)obj).id == id;
}
#Override
public int hashCode()
{
return id;
}
}
//Then change this in ComponentObject<T>:
public class ComponentObject<T>
{
//add this field:
private final OwnershipToken ownershipToken;
//add this constructor
public ComponentObject(OwnershipToken onwershipToken)
{
this.ownershipToken = ownershipToken;
}
//change restricted_to_owner_only signature:
public Object restricted_to_owner_only(OwnershipToken ownershipToken)
{
//add this condition
if(this.ownershipToken.equals(ownershipToken)
//something;
}
}
//finally, Owner gains a field:
public class Owner
{
private final OwnershipToken ownershipToken = new OwnershipToken();
//... etc, remainder of the class
}
would this work as intended?
I understand what you want and that is impossible i think.
But, there is still one way to do it!
Make an id in the owner class:
private int id = new Random().nextInt(10000);
In ComponentObject:
private id;
public ComponentObject(int id){
this.id = id;
}
public Object restricted(int id){
if(this.id != id)
return null;
else
return object;
}
In owner:
private ComponentObject<String> string;
public Owner() {
string = new ComponentObject<>(id);
string.restricted(id);
//if the id is right it will return the restricted object, if not i will
//return null
}

Public static final variable with getter

at work we do a peer review of code and I found something I don't like and I want to ask about best practice for this particular problem.
We have an interface:
public interface Item {
public String getType();
//some other methods
}
and an implementing class:
public class EmailItem implements Item {
public static final String TYPE = "email";
#Override
public String getType() {
return TYPE;
}
}
and some code that uses the classes:
for (Item item : items) {
if (EmailItem.TYPE.equals(item.getType())) {
isProcessed = Processor.process(item);
} else {
LOGGER.error("Unknown failover type received to process. Type: {}", item.getType());
}
}
At this point we have only one implementing class so checking the type is not necessary but we will add some other implementations and then it would make sense (though switch will be used).
The main issue is that EmailItem has variable TYPE set as public and this variable has also a getter.
Both class and instance of that class should have access to this variable, but having it public static final and accessing it with instance directly doesn't seem right/best practice (although it is technically possible) and when it would be private (as it should) then it won't be accessible from other classes (where for cycle is and static would not make sense at that point).
Through discussion we come up with solution with usage of instanceOf(...) or instance.getClass().getName() and EmailItem.class.getName() but none of them seem elegant to me :).
So finally, my question is what is the most elegant solution for described problem?
Heh, this is my first question here and I hope it makes sense to you ;).
Thinking about it from an OO point of view I'd consider the following approach:
public interface Item {
public boolean process();
//some other methods
}
public class EmailItem implements Item {
#Override
public boolean process() {
// email specific implementation
}
}
public class AnotherItem implements Item {
#Override
public boolean process() {
// another implementation
}
}
for (Item item : items) {
isProcessed = item.process();
}
The way you did it is fine, if you want to do it that way:
The static final variable TYPE lets you treat it as a type constant,
The implementation on the instance lets you check the constant against the return value on the interface.
However, when you find yourself dispatching on a type represented by String or some other value, you are usually going down a wrong path of switch statements in object-oriented code. If you have a choice of action at this point, consider an alternative technique of double dispatch, such as implementing the Visitor Pattern:
interface ItemVisitor {
void visitEmail(EmailItem item);
void visitSms(SmsItem item);
}
interface Item {
void accept(ItemVisitor v);
}
class EmailItem implements Item {
public void accept(ItemVisitor v) { v.visitEmail(this); }
}
class SmsItem implements Item {
public void accept(ItemVisitor v) { v.visitSms(this); }
}
Now you can do this:
class Example implements ItemVisitor {
public void visitEmail(EmailItem item) {
// Do something with an e-mail
}
public void visitSms(SmsItem item) {
// Do something with an SMS
}
public static void main(String[] args) {
Example e = new Example();
for (Item item : ItemSource.getManyItems()) {
item.accept(e);
}
}
}
If all "types" for your Item are known at compile time, you could use an enum like this:
public interface Item {
enum ItemType { MAIL, OTHER; }
public ItemType getType();
//some other methods
}

Generics in Java preventing calling of methods

So I have custom class that looks like this:
public class Cell {
protected boolean wasActive;
public Cell() {
this.wasActive = false;
}
public boolean getPreviousActiveState() {
return this.wasActive;
}
public void setPreviousActiveState(boolean previousActiveState) {
this.wasActive = previousActiveState;
}
}
Now I am writing another class here I need to call the above getPreviousActiveState() method:
public class Synapse<Cell> {
private Cell cell;
// some other methods... like isConnected
public boolean getPreviousActiveState() {
this.cell.getPreviousActiveState; // <= CAN'T BE CALLED. WHY?
}
}
I know the problem has to do with the fact that I declared the class:
public class Synapse<Cell>
but I did this so that only a Synapse can only contain a subclass of Cell. For example I also have implemented a VisionCell, AudioCell, and Neuron class that all extend Cell. Was this use of generics unneccesary? If so, when should I use generics? Thanks!
Defining a type parameter called Cell means is creating some confusion. Let's rename it to T, and also add the pair of missing parenthesis to the this.cell.getPreviousActiveState call:
class Synapse<T> {
private T cell;
// some other methods... like isConnected
public boolean getPreviousActiveState() {
return this.cell.getPreviousActiveState(); // <= CAN'T BE CALLED. WHY?
}
}
The error that you now get is:
The method getPreviousActiveState() is undefined for the type T
Which is the compiler's way of telling you that no where in the code it guaranteed that type parameter T has a getPreviousActiveState() method. Note that Java generic are not like C++ templates: the generic class is compiled once independently of any calling site. In other words: the compiler does not check this class w.r.t to any particular instantiation, but rather it checks that it makes sense on its own.
In order to guarantee that T has a getPreviousActiveState() all you need to do is to specify an upper bound on T that defines this method. We can use Cell itself:
class Synapse<T extends Cell> {
private T cell;
// some other methods... like isConnected
public boolean getPreviousActiveState() {
return this.cell.getPreviousActiveState(); // <= Compiles!
}
}
Of course, you can make the code more versatile by introducing an interface defining the method(s) you're interested in and using this interface as the upper bound. You will also have to make Cell implement this interface:
interface ActiveStateProvider {
public boolean getPreviousActiveState();
}
class Cell implements ActiveStateProvider {
protected boolean wasActive;
public Cell() {
this.wasActive = false;
}
public boolean getPreviousActiveState() {
return this.wasActive;
}
public void setPreviousActiveState(boolean previousActiveState) {
this.wasActive = previousActiveState;
}
}
class Synapse<T extends ActiveStateProvider> {
private T cell;
// some other methods... like isConnected
public boolean getPreviousActiveState() {
return this.cell.getPreviousActiveState(); // <= Compiles!
}
}

Modifying the return value of an abstract method during runtime

Is it possible to modify the return value of an abstract method during runtime?
For instance:
public abstract class Task {
public abstract boolean validate();
public void setValidate(boolean b) {
/* modify the return value of 'validate' method */
}
}
Why not just have a boolean field in Task, have validate return the value of that field, and have setValidate change that value?
public abstract class Task {
private boolean isValid;
public boolean validate() { return isValid; }
public void setValidate(boolean b) { isValid = b; }
}
Alas, if only you could (easily, anyway). But there is a workaround if you can modify the abstract class and subclasses. Make subclasses implement a protected method instead, then make it so that your validate() method checks the value of the validate before validating. You should probably also make validate() a final method, as I have in the example, so that subclasses can't change it to not check the variable. This is up to you, of course.
Here's the code for the workaround:
public abstract class Task {
private boolean validate = true;
public final boolean validate() {
// Assumes that no validation means validation always passes
return validate ? validateImpl() : true;
}
protected abstract boolean validateImpl();
public void setValidate(boolean validate) {
this.validate = validate;
}
}

Enforcing dynamic polymorphic calls with general parent type input arguments

I am trying to use polymorphism to enable different processing of an object based on its class, as follows:
public class GeneralStuff {
private int ID;
}
public class IntStuff extends GeneralStuff {
private int value;
public void setValue(int v)
{
value = v;
}
public int getValue()
{
return value;
}
}
public class DoubleStuff extends GeneralStuff {
private double value;
public void setValue(double v)
{
value = v;
}
public double getValue()
{
return value;
}
}
public class ProcessStuff {
public String process(GeneralStuff gS)
{
return doProcess(gS);
}
private String doProcess(IntStuff i)
{
return String.format("%d", i.getValue());
}
private String doProcess(DoubleStuff d)
{
return String.format("%f", d.getValue());
}
}
public class Test {
public static void main(String[] args)
{
IntStuff iS = new IntStuff();
DoubleStuff dS = new DoubleStuff();
ProcessStuff pS = new ProcessStuff();
iS.setValue(5);
dS.setValue(23.2);
System.out.println(pS.process(iS));
System.out.println(pS.process(dS));
}
}
This, however, doesn't work, because calling doProcess(gS) expects a method with a signature doProcess(GeneralStuff gS).
I know I could just have two exposed polymorphic process methods in the ProcessStuff class, but the actual situation won't allow it because I'm working within the constraints of an existing library mechanism; this is just a contrived example for testing.
I could, of course, define process(GeneralStuff gS) as
public String process(GeneralStuff gS)
{
if (gS instanceof IntStuff)
{
return doProcess((IntStuff) gS);
}
else if (gS instanceof DoubleStuff)
{
return doProcess((DoubleStuff) gS);
}
return "";
}
which works, but it seems that I shouldn't have to do that (plus, the Programming Police would skewer me for using instanceof in this way).
Is there a way that I can enforce the polymorphic calls in a better way?
Thanks in advance for any help.
The type of dynamic dispatch you are looking for is not possible in Java without using reflection. Java does its linking at compile time based on the declared type (so even though a method is overloaded, the actual method invoked is based on the declared type of the variable not the runtime type).
So you are left with either using instanceof as you propose, using reflection, or putting the process methods in the objects themselves (which is the "oop" way to do it, but is often not suitable or advisable).
One potential alternative is to create a map of processing objects by class, eg:
Map<Class<? extends GeneralStuff>,Processor> processors;
public String process(GeneralStuff stuff)
{
Processor processor = processors.get(stuff.getClass());
if (processor != null)
{
return processor.process(stuff);
}
}
public interface Processor
{
public String process(GeneralStuff stuff);
}
public class IntegerProcessor implements Processor
{
public String process(GeneralStuff stuff)
{
return String.format("%i",((IntegerStuff) stuff).getValue());
}
}
However, for your specific example, String.format takes objects as the parameters, so you could avoid this whole issue by having getValue and getFormatString methods in GeneralStuff which are overriden in the specific subclasses.
You are actually on the right track, you indeed need to use reflection in this case. What you are looking for is sort of double dispatch, because you want the dispatch to be done on the dynamic type of the stuff parameter.
This type of switching-on-dynamic-type is not as rare as you think. See for example this javaworld tipe, which reflects on the visitor pattern
The compiler complains for good reason. There is no guarantee that your GeneralStuff object is an IntStuff or a DoubleStuff. It can be a plain GeneralStuff or any other extension of GeneralStuff, which is a case you also did not cover in your process method with the instanceof (unless returning the empty String was the desired behavior).
Is it not possible to move that process method into the GeneralStuff class and override it in the extensions ?
Another possible solution is to have a sort of composite ProcessStuff class in which you plug a IntStuffProcess, DoubleStuffProcess, ... instance . Each of those instances will still have the instanceof check to decide whether they can handle the GeneralStuff object passed to them, but this is at least more scalable/maintainable then one big instanceof construct
Perhaps, it's better to have overloaded process method in ProcessStuff:
public class ProcessStuff {
private String process(IntStuff i) {
return String.format("%d", i.getValue());
}
private String process(DoubleStuff d) {
return String.format("%f", d.getValue());
}
}
Define an GeneralStuff as an abstract class, with a doProcess method (abstract) which is filled in in the inheriting classes. This way you avoid all problems with instanceof values and such. Or you can do what is suggested by βнɛƨн Ǥʋяʋиɢ, but then you still would have to define an overload for each specific class, whereas in mine you just call it directly.
So my suggestion would be:
public abstract class GeneralStuff {
private int ID;
public abstract String process();
}
public class IntStuff extends GeneralStuff {
private int value;
public void setValue(int v)
{
value = v;
}
public int getValue()
{
return value;
}
#override
public String process(){
return String.format("%d", getValue());
}
}
public class DoubleStuff extends GeneralStuff {
private double value;
public void setValue(double v)
{
value = v;
}
public double getValue()
{
return value;
}
#override
public String process(){
return String.format("%f", getValue());
}
}
public class Test {
public static void main(String[] args)
{
IntStuff iS = new IntStuff();
DoubleStuff dS = new DoubleStuff();
ProcessStuff pS = new ProcessStuff();
iS.setValue(5);
dS.setValue(23.2);
System.out.println(iS.process());
System.out.println(dS.process());
}
}

Categories