How to Ignore Overriding - java

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

Related

Can only access Parent class variables from method

So the issue I'm running into is this. I've written a method as a part of a program that I'm using to display all the objects in an ArrayList. There are three different types of objects stored in this ArrayList: Fungus, Flowers and Weeds. I'm able to call plantList.get(i).getName() and plantList.get(i).getColor methods with no issue. Both of these variables belong to the parent class called Plant. However, when calling the following method plantList.get(i).getPoison() (this method belongs to the subclass Fungus) I get a compiler error saying that it cannot find the variable Fungus.
I've tried it with every other variable unique to a subclass, and the same things happens. So I can access variables from the parent class 'Plant' but not from any of the subclasses of 'Fungus' 'Flower' or 'Weed'. I'm new to using subclasses and superclasses so I'm having a hard time figuring out exactly where the issue is arising.
public static void displayPlant(ArrayList<Plant> plantList) {
for (int i = 0; i < plantList.size(); i++) {
System.out.print(plantList.get(i).getName());
System.out.print(plantList.get(i).getID());
System.out.print(plantList.get(i).getColor());
if (plantList.get(i).contains(Fungus) == true) {
System.out.print(plantList.get(i).getPoison());
}
else if (plantList.get(i).contains(Flower) == true) {
System.out.print(plantList.get(i).getSmell());
System.out.print(plantList.get(i).getThorns());
}
else {
System.out.print(plantList.get(i).getPoison());
System.out.print(plantList.get(i).getEdible());
System.out.print(plantList.get(i).getMedicinal());
}
}
}
A good solution is to use dynamic dispatch. I.e. let the element itself decide what information it wants to print.
class Plant {
...
public String toString() {
return String.join(" ", getName(), getID(), getColor());
}
}
class Fungus extends Plant {
...
#Override
public String toString() {
return String.join(" ", super.toString(), getPoison());
}
}
class Flower extends Plant {
...
#Override
public String toString() {
return String.join(" ", super.toString(), getSmell(), getThorns());
}
}
class Weed extends Plant {
...
#Override
public String toString() {
return String.join(" ", super.toString(), getPoison(), getEdible(), getMedicinal());
}
}
Your loop will look like this:
public static void displayPlant(ArrayList<Plant> plantList) {
for(Plant p : plantList)
System.out.println(p); // This calls toString
}
Actually you are doing it in a wrong way,
Once you keep the object of child class into parent class variable then at compile time it search or find only the methods and variables that are declared in the parent class.
if you want to access the child class variables then you need to first find out the child class and then typecast it according
public static void displayPlant(ArrayList<Plant> plantList) {
for (int i = 0; i < plantList.size(); i++) {
Plant plant=plantList.get(i);
if (plant instanceof Flowers) {
Flowers fl=(Flowers)plant;
//TODO do whatever you want to do
}
else if(plant instanceof Weeds) {
Weeds wd=(Weeds)plant;
//TODO do whatever you want to do
}else if (plant instanceof Fungus) {
Fungus wd=(Fungus)plant;
//TODO do whatever you want to do
}
}
I hope it help you out. Thanks
Java is strongly typed language. That means that, if you want to use methods of child class you have to cast down to child class.
In your example:
...
else if (plantList.get(i) instanceof Fungus) { //check if plant is fungus
System.out.print(plantList.get(i).getSmell());
System.out.print(((Fungus)plantList.get(i)).getThorns()); //downcasting
}
...
Your check using constains wouldn't work. To check type of object you need to use operator instanceof.

Why is this method not recursive?

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.

Which method should change the field, when calling a hierarcy of private methods?

When a class' public method needs to call a private method that results in a field being changed, which method should change the field? Is there any common convention for this? Is one approach preferable over the other?
Consider these two code snippets:
public class boolHolder {
private boolean theBool = false;
public void doYourThing() {
// Do a lot of other stuff
setBool();
}
private void setBool() {
// Do a lot of other stuff, justifying a private method for this
this.theBool = true;
}
}
VS
public class boolHolder {
private boolean theBool = false;
public void doYourThing() {
// Do a lot of other stuff
theBool = setBool();
}
private boolean setBool() {
// Do a lot of other stuff, justifying a private method for this
return true;
}
}
These two snipped of course being a very simple case, but I'm sure I'm not the only one ending up with public methods calling a huge tree of private methods. Should the field be set at the end of the branch, or should a value be passed back?
I think it makes more sense that only a single place would set the value of the field, and it should be the last method being called. It makes the code easier to understand. Your first snippet looks much more readable to me.
Here's another snippet which, in my opinion, supports this convention :
Lets say we have an int member with two setters - one accepts an int and the other accepts a String representation of that int (which is used, for example, if we de-serialize an instance from an XML String).
int value;
public void setIntField (String value)
throws SomeException
{
if (value == null)
throw new SomeException();
try {
int val = Integer.parseInt (value);
setIntField (val);
}
catch (NumberFormatException ex) {
throw new SomeException();
}
}
public void setIntField (int value)
throws SomeException ()
{
if (value < MIN_ALLOWED || value > MAX_ALLOWED)
throw new SomeException ();
this.value = value;
}
Apart from renaming theBool and setBool to something more understandable (which I'm going to assume you did eitherway in the real application), I'd go with the first one. Methods with the word set are expected to be setters and not many people will expect a return value.
It doesn't change much, but you can try to use a better naming for your methods: i don't like that you name your second method setBool().
If you write "Do a lot of other stuff, justifying a private method for this" you can try to associate a verb to that stuff you do.
Say you update an account status and upon completion want to signal with the boolean the status, well use something like what you did but call it in a meaningful way, e.g. updateAccount() and either return a true if the update went fine or set it inside:
public class boolHolder {
private boolean accountUpdated = false;
public void doYourThing() {
// Do a lot of preliminary stuff
updateAccount();
}
private void updateAccount() {
// try to update account
// if update went fine
this.accountUpdated = true;
}
}
or
public class boolHolder {
private boolean accountUpdated = false;
public void doYourThing() {
// Do a lot of preliminary stuff
this.accountUpdated = updateAccount();
}
private boolean updateAccount() {
// try to update account
// if error happens, rollback change and set
return false;
// else (update went fine)
return true;
}
}
are both perfectly fine, but make your method tell what they do, since updating the bool is not the main action since you "Do a lot of other stuff, justifying a private method for this".
The value setting inside is more compact if you use a default to false as you did, but the other is more explicit in what it does. So I tend to prefer that: returning a result for you operation.

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).

Array of function pointers in Java [duplicate]

This question already has answers here:
How to call a method stored in a HashMap? (Java) [duplicate]
(3 answers)
Closed 8 years ago.
I have read this question and I'm still not sure whether it is possible to keep pointers to methods in an array in Java. If anyone knows if this is possible (or not), it would be a real help. I'm trying to find an elegant solution of keeping a list of Strings and associated functions without writing a mess of hundreds of if statements.
Cheers
Java doesn't have a function pointer per se (or "delegate" in C# parlance). This sort of thing tends to be done with anonymous subclasses.
public interface Worker {
void work();
}
class A {
void foo() { System.out.println("A"); }
}
class B {
void bar() { System.out.println("B"); }
}
A a = new A();
B b = new B();
Worker[] workers = new Worker[] {
new Worker() { public void work() { a.foo(); } },
new Worker() { public void work() { b.bar(); } }
};
for (Worker worker : workers) {
worker.work();
}
You can achieve the same result with the functor pattern. For instance, having an abstract class:
abstract class Functor
{
public abstract void execute();
}
Your "functions" would be in fact the execute method in the derived classes. Then you create an array of functors and populate it with the apropriated derived classes:
class DoSomething extends Functor
{
public void execute()
{
System.out.println("blah blah blah");
}
}
Functor [] myArray = new Functor[10];
myArray[5] = new DoSomething();
And then you can invoke:
myArray[5].execute();
It is possible, you can use an array of Method. Grab them using the Reflection API (edit: they're not functions since they're not standalone and have to be associated with a class instance, but they'd do the job -- just don't expect something like closures)
Java does not have pointers (only references), nor does it have functions (only methods), so it's doubly impossible for it to have pointers to functions. What you can do is define an interface with a single method in it, have your classes that offer such a method declare they implement said interface, and make a vector with references to such an interface, to be populated with references to the specific objects on which you want to call that method. The only constraint, of course, is that all the methods must have the same signature (number and type of arguments and returned values).
Otherwise, you can use reflection/introspection (e.g. the Method class), but that's not normally the simplest, most natural approach.
I found the reflection approach the cleanest -- I added a twist to this solution since most production classes have nested classes and I didn't see any examples that demonstrates this (but I didn't look for very long either). My reason for using reflection is that my "updateUser()" method below had a bunch of redundant code and just one line that changed (for every field in the user object) in the middle that updated the user object:
NameDTO.java
public class NameDTO {
String first, last;
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
}
UserDTO.java
public class UserDTO {
private NameDTO name;
private Boolean honest;
public UserDTO() {
name = new NameDTO();
honest = new Boolean(false);
}
public NameDTO getName() {
return name;
}
public void setName(NameDTO name) {
this.name = name;
}
public Boolean getHonest() {
return honest;
}
public void setHonest(Boolean honest) {
this.honest = honest;
}
}
Example.java
import java.lang.reflect.Method;
public class Example {
public Example () {
UserDTO dto = new UserDTO();
try {
Method m1 = dto.getClass().getMethod("getName", null);
NameDTO nameDTO = (NameDTO) m1.invoke(dto, null);
Method m2 = nameDTO.getClass().getMethod("setFirst", String.class);
updateUser(m2, nameDTO, "Abe");
m2 = nameDTO.getClass().getMethod("setLast", String.class);
updateUser(m2, nameDTO, "Lincoln");
m1 = dto.getClass().getMethod("setHonest", Boolean.class);
updateUser(m1, dto, Boolean.TRUE);
System.out.println (dto.getName().getFirst() + " " + dto.getName().getLast() + ": honest=" + dto.getHonest().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateUser(Method m, Object o, Object v) {
// lots of code here
try {
m.invoke(o, v);
} catch (Exception e) {
e.printStackTrace();
}
// lots of code here -- including a retry loop to make sure the
// record hadn't been written since my last read
}
public static void main(String[] args) {
Example mp = new Example();
}
}
You are right that there are no pointers in java because a reference variables are the same as the & syntax in C/C++ holding the reference to the object but no * because the JVM can reallocate the heap when necessary causing the pointer to be lost from the address which would cause a crash. But a method is just a function inside a class object and no more than that so you are wrong saying there are no functions, because a method is just a function encapsulated inside an object.
As far as function pointers, the java team endorses the use of interfaces and nested classes which all fine and dandy, but being a C++/C# programmer who uses java from time to time, I use my Delegate class I made for java because I find it more convenient when I need to pass a function only having to declare the return type of the method delegate.
It all depends on the programmer.
I read the white pages on why delegates are not support but I disagree and prefer to think outside the box on that topic.

Categories

Resources