Why is this method not recursive? - java

I'm not quite sure how to ask this question without posting the whole code here (it's quite a bit), but I'll try my best.
I have an enum class which implements an interface. The purpose of the whole program is to represent a bunch of integer numbers in Fields. So there is a concrete class TrueField which is derived from abstract class AbstractField that has the implementation of a method called boolean sameAs(Field that). That method also exists (it has to, because of the interface) in the enum class:
enum SimpleField implements Field{
Empty(),Zero(0),Binary(0,1),Unsigned(Integer.MAX_VALUE);
private Field simpleField;
SimpleField(int... intArray){
simpleField = new TrueField(intArray);
}
#Override
public boolean sameAs(Field that){
return that.sameAs(simpleField);
}
}
Implementation from TrueField:
public class TrueField extends AbstractField{
private final int[] intArray;
TrueField(int... thatArray){
intArray = thatArray;
}
#Override
public int at(int index){
if(index<0 || index>=intArray.length){
throw new IndexOutOfBoundsException();
}
return intArray[index];
}
#Override
public int length(){
return intArray.length;
}
...
AbstractField:
public abstract class AbstractField implements Field{
#Override
public abstract int length();
#Override
public boolean sameAs(Field that){
if(that==null)
throw new RuntimeException("that is null");
boolean result = true;
if(length()==that.length()){
for(int i=0;i<length();i++){
if(at(i)!=that.at(i))
result = false;
}
}
else
result = false;
return result;
}
#Override
public String toString(){
String result = "";
for(int i=0;i<length();i++){
result += at(i);
if(length()-i>1)
result += ",";
}
return "["+result+"]";
}
}
My question is, when I do something like this in my main method:
Field sf = SimpleField.Binary;
Field sf2 = SimpleField.Binary;
Field tf = new TrueField(1,2);
System.out.println(sf.sameAs(sf2));
...obviously the method sameAs in the enum class gets called. But why isn't it calling itself again so it is recursive? As there is dynamic binding because of the interface the JVM sees that sf is the dynamic type SimpleField.Binary and the static type Field. I don't quite understand what's going on and why it isn't calling itself again. I hope I've explained my question clear enough.

It's not recursive because your sameAs method in the SimpleField enum calls the sameAs method of the parameter object, which is not a SimpleField, it's a TrueField.
So the sameAs method is being run as declared in the Field class.
On further inspection, it could be recursive, but only if the declaration in the TrueField class was recursive also, which we can see that it is not, now that this code has been added above.

The method isn't recursive because it's not calling itself.
#Override
public boolean sameAs(Field that){
return that.sameAs(simpleField);
}
This method is using the argument to call sameAs. The argument may very well be the same enum, but it's still not calling itself.
This is an example of a simple recursive method:
public long factorial(int value) {
return value == 0 ? 1 : factorial(value-1);
}
In this, there's no extra reference to use to call the method again; I'm just invoking it once more with a slight change in parameters.

Related

How to Ignore Overriding

Code first - question later
class A {
int value() { return 1; } //The value
int getThisValue() { return this.value(); } //gives back the overridden value
int getValue() { return value(); } //this too
int getSuperValue() { return value(); } //for overriding in B
final int getSuperValue2() { return getSuperValue(); }
//Here I get the not-overridden value
//TODO: simplify the process of getting the un-overridden value
}
class B extends A {
#Override
final int getSuperValue() { return super.value(); } //returns the correct value
}
public class Test extends B{
#Override
int value() { return 3; } //overriding the value
public static void main(String[] args) { //output
Test test = new Test();
System.out.println("getValue(): " + test.getValue()); //3
System.out.println("getThisValue(): " + test.getThisValue()); //3
System.out.println("getSuperValue(): " + test.getSuperValue()); //1
System.out.println("getSuperValue2(): " + test.getSuperValue2()); //1
}
}
I have A class, in which I access value.
This value gets overridden
-> I want to access the un-overrridden value in A
My Question: Is getSuperValue2() the only way get the un-overridden value or is there another way?
I want to know if I can protect my Code, by only accessing Code I know, but making my code overrideable for those, that want to change the functionality a bit
There is indeed no way once a subclass starts overriding. That's by design - you don't get to refer to "The implementation of the getValue() method the way class A does it", that's the wrong mental model. You merely get to refer to the notion of "the implementation of the getValue() method the way this object does it" (note the difference: Think 'objects', not 'classes'). Once we talk solely about 'the impl from this object', then the idea of "But I want the unoverridden value" no longer makes any sense, hence why you can't do it.
want to know if I can protect my Code
Yeah of course. Just mark the method final! This is a sometimes-observed pattern:
public class Parent {
public final void init() {
childInit();
doStuffThatChildClassesCannotStopFromHappening();
}
protected void childInit() {
// does nothing - child classes can override if they wish
}
}

Constructor in abstract and non-abstract classes

I have a GenericContainer class and a FIFOContainer class that extends the generic one. My problem appears when trying to use the takeout() method. It does not recognize that I hold values in my FIFOContainer ArrayList.
I suspect this has something to do with how I defined the constructors but for the life of me cannot figure it out how to solve it.
A solution I thought of is defining a getter in the GenericContainer class and passing the value in the FIFOContainer class but I feel like this should not be needed.
public abstract class GenericContainer implements IBag {
private ArrayList<ISurprise> container;
public GenericContainer() {
this.container = new ArrayList<ISurprise>();
}
#Override
public void put(ISurprise newSurprise) {
this.container.add(newSurprise);
}
#Override
public void put(IBag bagOfSurprises) {
while (!bagOfSurprises.isEmpty()) {
System.out.println(bagOfSurprises.size());
this.container.add(bagOfSurprises.takeout());
}
}
#Override
public boolean isEmpty() {
if (this.container.size() > 0) {
return false;
}
return true;
}
#Override
public int size() {
if (isEmpty() == false) {
return this.container.size();
}
return -1;
}
}
public class FIFOContainer extends GenericContainer {
private ArrayList<ISurprise> FIFOcontainer;
public FIFOContainer() {
super();
this.FIFOcontainer = new ArrayList<ISurprise>();
}
public ISurprise takeout() {
if (isEmpty() == false) {
this.FIFOcontainer.remove(0);
ISurprise aux = this.FIFOcontainer.get(0);
return aux;
}
return null;
}
}
Thing is: fields are not poylmorphic (see here for example).
Your problem: basically your isEmpty() will use the container in the base class, and the other method will us the container in the subclass.
Yes, there are two containers in your class.
A better approach could be to (for example) do this in the base class GenericContainer:
protected abstract List<ISurprise> getContainer();
In other words: a subclass could provide its own container, and base methods as isEmpty() could use that one:
#Override
public final boolean isEmpty() {
return getContainer().isEmpty();
}
To allow for more degrees of freedom, that method could also have a slightly different signature, such as protected abstract Collection<ISurprise> to be more flexible about the actual implementation.
( hint: I made the method final, as that is the whole idea of methods defined in an abstract base class: that subclasses do not overwrite them )
( and bonus hints: try to minimize the amount of code that you write. you don't do someBool == true/false, you don't need to do getSize() == 0 when that list class already offers you an isEmpty() method )
You shouldn't create new arraylist in FIFOContianer. you already have list from GenericContainer.
So right now, when you are calling put it adds item to the container list in the parent class. when calling takeout you are accessing other list (FIFOcontainer) which you created in the child class.
just remove FIFOcontainer and keep using container:
public ISurprise takeout() {
if (isEmpty() == false) {
this.container.remove(0);
ISurprise aux = this.container.get(0);
return aux;
}
return null;
}

Passing Anonymous Classes

This is a question for Java. I have an interface called IMyObjectPredicate which implements a single test method to apply to an input:
public interface IMyObjectPredicate {
boolean test(MyObject x);
}
What I would like is to be able to pass an instance of IMyObjectPredicate around between objects and have the test function update its references to variables to those of the new object it is being passed to. For instance, consider a class which makes use of this predicate:
public class Tester {
MyObject o;
IMyObjectPredicate myTestFunction;
int myThreshold;
public Tester(/*stuff*/) {
/*Code here which initialises the Tester instance and 'myThreshold'*/
myTestFunction = new IMyObjectPredicate() {
#Override
public boolean test(MyObject o) {
return (o.value() > myThreshold);
}
};
}
public boolean isGood() {
return myTestFunction.test(o);
}
}
I would like to be able to perform a deep clone of the Tester object for reasons I won't go into here. But the idea is that the cloned instance of Tester should test the predicate against its own value of myThreshold, not reference the myThreshold of the first instance. But if I pass myTestFunction to a new instance of Tester, I guess it will still be referencing the myThreshold value of the first instance, instead of dynamically evaluating myThreshold based on the reference of the enclosing class.
How can I accomplish the passing of a IMyObjectPredicate object whose test function uses references to the fields of the new object it is passed to?
Edit:
A complicating factor is that, in general, it will not be possible to reconstruct myTestFunction solely from the fields within a Tester object. myTestFunction may be overwritten by other parts of the program in a way that does not correlate with the other fields of Tester. I can sacrifice this functionality if need be, but I would rather not for the sake of elegance.
Java does not have an API to replace enclosed context of anonymous class.
The simplest solution I can see from your simplified example is to add threshold to the signature of test function. As I understand the threshold is going to be there anyway.
public interface IMyObjectPredicate {
boolean test(MyObject x, int threshold);
}
Another approach would use some factory method that will create a predicate for provided threshold like
class PredicateFactory {
IMyObjectPredicate thresholdPredicate(int threshold) {
return new IMyObjectPredicate {
//...
}
}
}
then you can pas this factory to object that will use it's own threshold to construct new instance of predicate
factory.thresholdPredicate(myThreshold);
It is a lot easier if ImObjectPredicate is an class that simply stores a reference to a predicate instead of an interface. If you're able to make that change, each predicate can store its own threshold, which solves the issue.
public IMyObjectPredicate {
private int threshold;
private Predicate<MyObject> pred;
public int getThreshold() {
return threshold;
}
public Predicate<MyObject> getPredicate() {
return pred;
}
public IMObjectPredicate(int threshold, Predicate<MyObject> pred) {
this.threshold = threshold;
this.pred = pred;
}
public boolean test(MyObject o) {
return pred.test(o);
}
}
public class Tester {
MyObject o;
IMyObjectPredicate myTestFunction;
IMyObjectPredicate myTestFunctionCopyWithDiffThreshold;
int myThreshold;
public Tester(/*stuff*/) {
/*Code here which initialises the Tester instance and 'myThreshold'*/
myTestFunction =
new IMyObjectPredicate(myThreshold, o -> o.value() > getThreshold());
myTestFunctionCopyWithDiffThreshold =
new ImObjectPredicate(5, myTestFunction.getPredicate());
}
public boolean isGood() {
return myTestFunction.test(o);
}
}
This is the most sensible solution, as ImObjectPredicate should store its own threshold if that value uniquely refers to that ImObjectPredicate.

Extending a java ArrayList

I'd like to extend ArrayList to add a few methods for a specific class whose instances would be held by the extended ArrayList. A simplified illustrative code sample is below.
This seems sensible to me, but I'm very new to Java and I see other questions which discourage extending ArrayList, for example Extending ArrayList and Creating new methods. I don't know enough Java to understand the objections.
In my prior attempt, I ending up creating a number of methods in ThingContainer that were essentially pass-throughs to ArrayList, so extending seemed easier.
Is there a better way to do what I'm trying to do? If so, how should it be implemented?
import java.util.*;
class Thing {
public String name;
public int amt;
public Thing(String name, int amt) {
this.name = name;
this.amt = amt;
}
public String toString() {
return String.format("%s: %d", name, amt);
}
public int getAmt() {
return amt;
}
}
class ThingContainer extends ArrayList<Thing> {
public void report() {
for(int i=0; i < size(); i++) {
System.out.println(get(i));
}
}
public int total() {
int tot = 0;
for(int i=0; i < size(); i++) {
tot += ((Thing)get(i)).getAmt();
}
return tot;
}
}
public class Tester {
public static void main(String[] args) {
ThingContainer blue = new ThingContainer();
Thing a = new Thing("A", 2);
Thing b = new Thing("B", 4);
blue.add(a);
blue.add(b);
blue.report();
System.out.println(blue.total());
for (Thing tc: blue) {
System.out.println(tc);
}
}
}
Nothing in that answer discourages extending ArrayList; there was a syntax issue. Class extension exists so we may re-use code.
The normal objections to extending a class is the "favor composition over inheritance" discussion. Extension isn't always the preferred mechanism, but it depends on what you're actually doing.
Edit for composition example as requested.
public class ThingContainer implements List<Thing> { // Or Collection based on your needs.
List<Thing> things;
public boolean add(Thing thing) { things.add(thing); }
public void clear() { things.clear(); }
public Iterator<Thing> iterator() { things.iterator(); }
// Etc., and create the list in the constructor
}
You wouldn't necessarily need to expose a full list interface, just collection, or none at all. Exposing none of the functionality greatly reduces the general usefulness, though.
In Groovy you can just use the #Delegate annotation to build the methods automagically. Java can use Project Lombok's #Delegate annotation to do the same thing. I'm not sure how Lombok would expose the interface, or if it does.
I'm with glowcoder, I don't see anything fundamentally wrong with extension in this case--it's really a matter of which solution fits the problem better.
Edit for details regarding how inheritance can violate encapsulation
See Bloch's Effective Java, Item 16 for more details.
If a subclass relies on superclass behavior, and the superclass's behavior changes, the subclass may break. If we don't control the superclass, this can be bad.
Here's a concrete example, lifted from the book (sorry Josh!), in pseudo-code, and heavily paraphrased (all errors are mine).
class CountingHashSet extends HashSet {
private int count = 0;
boolean add(Object o) {
count++;
return super.add(o);
}
boolean addAll(Collection c) {
count += c.size();
return super.addAll(c);
}
int getCount() { return count; }
}
Then we use it:
s = new CountingHashSet();
s.addAll(Arrays.asList("bar", "baz", "plugh");
And it returns... three? Nope. Six. Why?
HashSet.addAll() is implemented on HashSet.add(), but that's an internal implementation detail. Our subclass addAll() adds three, calls super.addAll(), which invokes add(), which also increments count.
We could remove the subclass's addAll(), but now we're relying on superclass implementation details, which could change. We could modify our addAll() to iterate and call add() on each element, but now we're reimplementing superclass behavior, which defeats the purpose, and might not always be possible, if superclass behavior depends on access to private members.
Or a superclass might implement a new method that our subclass doesn't, meaning a user of our class could unintentionally bypass intended behavior by directly calling the superclass method, so we have to track the superclass API to determine when, and if, the subclass should change.
I don't think extending arrayList is necessary.
public class ThingContainer {
private ArrayList<Thing> myThings;
public ThingContainer(){
myThings = new ArrayList<Thing>();
}
public void doSomething(){
//code
}
public Iterator<Thing> getIter(){
return myThings.iterator();
}
}
You should just wrap ArrayList in your ThingContainer class. ThingContainer can then have any processing methods you need. No need to extend ArrayList; just keep a private member.
Hope this helps.
You may also want to consider creating an interface that represents your Thing Class. This gives you more flexibility for extensibility.
public Interface ThingInterface {
public void doThing();
}
...
public OneThing implements ThingInterface {
public void doThing(){
//code
}
}
public TwoThing implements ThingInterface {
private String name;
public void doThing(){
//code
}
}
Here is my suggestion:
interface ThingStorage extends List<Thing> {
public int total();
}
class ThingContainer implements ThingStorage {
private List<Thing> things = new ArrayList<Thing>();
public boolean add(Thing e) {
return things.add(e);
}
... remove/size/... etc
public int total() {
int tot = 0;
for(int i=0; i < size(); i++) {
tot += ((Thing)get(i)).getAmt();
}
return tot;
}
}
And report() is not needed actually. toString() can do the rest.

java return from private method to public

I have a public method and a private method. they are both supposed to return int values. The private method is the one that does all the work and the public is the one that is called from the main program. How can I return the results returned from the private method by the public method?
its like this
public int longer()
{
longer(a.length);
}
private int longer(int n)
{
int index
//find largest index recursively
//make recursive call longer(n-1)
return index;
}
I want to pass it up to the public method and then return it from there. Would I just return it from the public method by saying return longer.index; or something along those lines?
i guess i should clarify. n isnt index. idnex is being calculated based on whats being passed into the method. the public and the private is because its going to be a recursive method. i'll edit what i posted above to make itm ore accurate of what im trying to do. passing in an array and recursively working on it.
public int longer()
{
return longerInternal(a.length);
}
private int longerInternal(int n)
{
int index
//find largest index recursively
//make recursive call longer(n-1)
return index;
}
From your public method, you can call down into the private method. I renamed the private method so that there was not a naming collision for your methods. A simple implementation should look something like this:
public class MyClass {
private int[] a;
public MyClass(int[] _a) {
a = _a;
}
public int longer()
{
return longerInternal(a.length);
}
private int longerInternal(int n)
{
int index;
//do recursive call
return index;
}
}
And it can be called like this:
MyClass myClass = new MyClass(new int[]{1,2,3,4,5,10});
int result = myClass.longer();
First, you probably need better function names.
You'd call your public function getLonger(int n) and then pass it to your private longer(int n) function. When this function is done, it will return to getLonger(int n) and then back to the caller.
You mentioned in an answer to a comment that the "caller does not need to have access to all internal workings of a class."
To me that suggests that you want to use an interface.
Create an interface that describes the class that will contain that secret algorithm:
package com.stevej;
public interface Longer {
public int longer();
}
Implement that interface using your secret algorithm:
package com.stevej;
public class LongerImpl implements Longer {
private int longer(int n){
return 0; // whatever
}
#Override
public int longer() {
return longer(5); // whatever
}
}
Now the caller only creates objects using the interface definition, guaranteeing that there are no exposed methods that he can access by accident. That implementation is hooked to that interface-defined object:
package com.stevej;
public class LongerProcessor {
Longer longerImpl = new LongerImpl();
public LongerProcessor() {
super();
}
public int longer() {
return longerImpl.longer();
}
}
Now you can rewrite the implementation of Longer as often as you like. As long as the interface definition never changes, the caller (LongerProcessor) will never have a problem. Heck, you could have two or more different implementations (LongerImplRecursive, LongerImplBruteForce, and so on), each implementing Longer, and all in use in different places in the same program:
package com.stevej;
public class LongerProcessor {
Longer longerImpl;
public LongerProcessor(boolean useRecursive) {
super();
if (useRecursive){
longerImpl = new LongerImplRecursive();
}else{
longerImpl = new LongerImplBruteForce();
}
}
public int longer() {
return longerImpl.longer();
}
}
How cool is that? Since you tagged this question as "homework", I'm wondering if the problem is supposed to engage you to think about separating the contract (interface) from the implementation (implementing class).

Categories

Resources